似乎Python osascript返回0

时间:2012-07-08 20:02:59

标签: python io terminal applescript

我正在尝试使用applescript来检索歌曲的BPM值。最终我想用游戏实现它。这是我的代码:

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

但这似乎只能工作一次......它得到我正在听的歌曲的BPM,看到它是94,然后它似乎在第二次迭代它认为它是0,然后它除以0然后死了。发生了什么事?

1 个答案:

答案 0 :(得分:1)

os.system 不会等待命令完成。

90 =是osascript的结果, 0 =没有错误,是退出状态( os.system )。

使用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)