从另一个脚本调用python脚本并获取特定值

时间:2017-01-16 19:07:03

标签: python

我使用以下代码获取WAV文件的BPMS: https://github.com/scaperot/the-BPM-detector-python/blob/master/bpm_detection/bpm_detection.py

我试图从我自己的脚本调用这个脚本但是因为bpm_detection.py只是打印(而不是返回任何东西)我可以得到底线值:

('')

我尝试通过添加一个可以调用的main()函数来编辑bpm_detection.py脚本。但是它让一些事情搞得一团糟而且bmp导致了Nan:

print 'Completed.  Estimated Beats Per Minute:', bpm

正如您所看到的,我添加了大量打印来调试它。似乎所有值都很好,直到max_window_nds得到0.0的下一行:

def main(filename, window):
    parser = argparse.ArgumentParser(description='Process .wav file to determine the Beats Per Minute.')
    parser.add_argument('--filename',
                    help='.wav file for processing')
    parser.add_argument('--window', type=float, default=3,
                    help='size of the the window (seconds) that will         be scanned to determine the bpm.  Typically less than 10 seconds. [3]')

    #args = parser.parse_args()
    samps, fs = read_wav(filename)
    print ("testing")
    #print (fs,samps)

    data = []
    correl = []
    bpm = 0
    n = 0
    nsamps = len(samps)
    print ("nsamps")
    print(nsamps)

    window_samps = int(window * fs)
    print ("window, window samp")
    print (window, window_samps)
    print ("fs")
    print (fs)

    samps_ndx = 0  # first sample in window_ndx
    max_window_ndx = nsamps / window_samps
    print ("max_window_nds")
    print (max_window_ndx)

    bpms = numpy.zeros(max_window_ndx)
    print ("bmps")
    print (bpms)

    # iterate through all windows
    for window_ndx in range(0, int(max_window_ndx)):

        # get a new set of samples
        # print n,":",len(bpms),":",max_window_ndx,":",fs,":",nsamps,":",samps_ndx
        data = samps[samps_ndx:samps_ndx + window_samps]
        if not ((len(data) % window_samps) == 0):
            raise AssertionError(str(len(data)))

        bpm, correl_temp = bpm_detector(data, fs)
        if bpm == None:
            continue
        bpms[window_ndx] = bpm
        correl = correl_temp

        # iterate at the end of the loop
        samps_ndx = samps_ndx + window_samps;
        n = n + 1;  # counter for debug...

    bpm = numpy.median(bpms)
    print('Completed.  Estimated Beats Per Minute:', bpm)
    return bpm

打印nsamps和window_samps导致: 6195200和333333

所以我没有找到我做错的事。我的最终目标是找到一种方法来获取bmp变量。

2 个答案:

答案 0 :(得分:0)

bpm_detection.py中的代码是为Python 2编写的,您可以在最终的print语句中找到它。您正在使用Python 3(也可以从您使用打印功能中看到)。 从Python 2变为Python 3并且必须移植的另一件事是除法运算符/。在Python 2中,如果两个操作数都是整数,则表示整数除法。在Python 3中,它总是返回一个浮点数。如果需要整数除法,则必须检查所有除法,然后使用Python 3整数除法运算符//。 请注意,这可能不是移植到Python 3的唯一方法。

答案 1 :(得分:0)

您是否真的需要直接访问变量,或者您仍然可以解析您调用的脚本实际打印的内容?因为您始终可以使用subprocess模块来调用另一个脚本。

import subprocess

p = subprocess.Popen(
    ['python','-u','bpm_detection.py',
    'arg_to_bmp_detection.py'], stdout=subprocess.PIPE)

prints_out = p.communicate()

如果你想要一些花哨的东西(比如进度条包装器),在你的主程序做一些等待子进程完成的事情时,使用一个线程来异步处理输出:Non-blocking read on a subprocess.PIPE in python