简体   繁体   English

Python osascript似乎返回0

[英]Python osascript returning 0 it seems

I'm trying to work with applescript for retrieving BPM values of songs. 我正在尝试使用applescript来检索歌曲的BPM值。 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. 但这似乎只起作用一次...它得到了我正在听的歌曲的BPM,看到是94,然后在第二次迭代中似乎以为是0,然后除以0并消失了。 What's going on? 这是怎么回事?

os.system doesn't wait for the command completes. os.system不等待命令完成。

90 = is the result of osascript , 0 = no error, is the exit status ( os.system ). 90 =是osascript的结果, 0 =没有错误,是退出状态( os.system )。

Use subprocess.Popen 使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM