Python osascript returning 0 it seems
Question: I'm trying to work with applescript for retrieving BPM values of songs.
Eventually I'd like to implement it with a game. Here's my code:

    
    
    import os
    import time
    import sys
    
    
    def getBPM():
        iTunesInstruct = """'
        tell application "iTunes"
        set k to get bpm of current track
        end tell
        return k
        '"""
        bpm = os.system('arch -i386 osascript -e ' + iTunesInstruct )
        #bpm =90
    
        bpm = int(bpm)
        bpm = round(bpm)
    
        if bpm > 250:
            bpm = 200
        return bpm
    
    
    def getBeatSecond(bpm):
        bps = float(bpm) / 60
        #raw_input(bps)
        return float(bps)
    
    i = 0
    
    beatMatch = True
    
    while True:
        beat = 1 / getBeatSecond(getBPM()) # BPS Beat divided by a second.
    
        if beatMatch:
            time.sleep(beat)
            print beat
        else:
            raw_input('Go??')
        i += 1
        if i > 50:
            break
    

But this seems to only work once... it got the BPM of the song I was listening
to, saw it was 94, and then it seems on the second iteration it thought it was
0, and then it divided by 0 and died. What's going on?


Answer: **os.system** doesn't wait for the command completes.

**90** = is the result of osascript , **0** = no error, is the exit status
(**os.system**).

Use `subprocess.Popen`

    
    
    from subprocess import Popen, PIPE
    
    def getBPM():
        cmd = "arch -i386 osascript -e " + """'tell application "iTunes" to return bpm of current track'"""
        bpm, tError = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate()
        if bpm > 250:
            return = 200
        return int(bpm)
    

