如何实现线程化以在python中运行两个bash shell命令? [英] How to implement threading to run two bash shell commands in python?

查看:294
本文介绍了如何实现线程化以在python中运行两个bash shell命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须记录一个wav文件,同时还要用sox分析它.我正在使用fifo类型文件执行此操作.

I have to record a wav file and at the same time I have to analyze it with sox. I am using fifo type file for this operation.

因此,在这里我需要同时启动2个线程,但是即使我使用这些线程,也无法实现我想做的事情.总是先执行,然后再执行.我希望它们并行运行,以便我可以做一些事情.

So here I need to start 2 threads at the same time but even if I use the threads I am not able to achieve what I wanna do. Always one executing first and then the other. I want them to be in parallel so that I can do some stuff.

#this should be in one thread
def test_wav(self):
    """ analyze the data """
    bashCommand = "sox {} -n stat".format(self.__rawfile)
    while self.__rec_thread.is_alive():
        process = subprocess.Popen(bashCommand.split(),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        wav_output = process.communicate()[1] #sox outputs the details in stderr
        #do something and return

#this should be in another thread
def record_wav(self):
    bashCommand = "arecord -d 10 -c 2 -r 48000 -f S32_LE > {}".format(self.__rawfile)
    pid = subprocess.Popen(bashCommand.split())
    pid.wait()
    if pid.returncode != 0:
        raise RecordException("Failed while recording with error {}".format(pid.returncode))

我尝试了以下代码使它们成为线程,但是失败了(总是先执行然后再执行另一个.我希望它们并行执行,以便我可以做一些事情). 导入的from threading import Thread

I tried the following code to make them threads but failed(Always one executing first and then the other. I want them to be in parallel so that I can do some stuff). imported from threading import Thread

self.__rec_thread = Thread(target = self.record_wav())
amp_thread = Thread(target = self.test_wav())
self.__rec_thread.start()
amp_thread.start()

首先,它完全执行记录(由于使用-d 10选项,因此至少需要10秒钟),然后才执行测试wav函数.就像一个接一个地叫他们.

First its executing the record(it minimum takes 10 sec because of the option -d 10) function completely and then the test wav function. Its like calling them one after another.

推荐答案

... target = self.record_wav() ...

调用 record_wav():它立即执行,并且直到record_wav()完成后程序才继续执行.您几乎总是希望将一个函数(或方法)对象传递给target=,几乎从不希望执行该函数/方法.因此,只需删除括号即可:

is calling record_wav(): it executes immediately, and the program doesn't proceed until record_wav() completes. You almost always want to pass a function (or method) object to target=, almost never the result of executing the function/method. So just lose the parentheses:

... target = self.record_wav ...

这篇关于如何实现线程化以在python中运行两个bash shell命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆