我必須記錄一個wav文件,同時我必須用sox來分析它。我正在使用fifo類型文件進行此操作。如何實現線程在python中運行兩個bash shell命令?
因此,我需要在同一時間啓動2個線程,但即使使用線程,我也無法實現我想要做的事情。總是先執行一個,然後執行另一個。我希望他們平行,以便我可以做一些事情。
#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
self.__rec_thread = Thread(target = self.record_wav())
amp_thread = Thread(target = self.test_wav())
self.__rec_thread.start()
amp_thread.start()
編輯:首先其執行記錄完全,然後(它最小花費,因爲該選項的10秒-d 10)功能的測試的wav功能。就像是一個接一個地給他們打電話。
你是什麼意思失敗?描述輸出或錯誤 –
@OferSadan總是先執行一個,然後執行另一個。我希望他們平行,以便我可以做一些事情。 – AQU
我不知道'sox'命令的作用是什麼,但是可能它運行得太快而不管它是否有線程?在每個函數的頂部添加一個print('thread 1 started')',並檢查輸出 –