[英]Python: Questions about subprocess, piped data, and multiprocessing
我有一個 Python 程序,它使用 Popen 調用測試 C++ 程序。 測試 C++ 程序只是將 0-99999 寫入標准輸出。 Python 程序有兩個功能應該作為單獨的進程運行。 一個 function,funcA,應該啟動 C++ 程序,從標准輸出 pipe 讀取整數,並將這些整數插入共享隊列。 另一個 function,funcB,應該讀取並打印隊列中的整數,直到隊列為空。 我有一些問題/問題,我將在下面發布,以及我的代碼。
我相信我目前針對問題 1 的方法有效,但我知道可能存在一些我沒有檢查的問題,例如隊列已滿。 此外,所有數字都沒有打印出來(停止在 98000 左右),我認為這可能與 funcA 終止和中斷共享隊列有關? 我不完全確定問題 2 該怎么做,因為文檔說在並發處理環境中不能依賴 empty(),我不想使用 while(1)。
import multiprocessing
import subprocess
import Queue
def funcA(intQueue):
# call C++ program
handle = subprocess.Popen(['../C++/C++.exe'], stdout=subprocess.PIPE)
while(handle.returncode == None):
handle.stdout.readline()
intQueue.put(handle.stdout.readline())
handle.poll()
def funcB(intQueue):
try:
while(1):
print intQueue.get(True, 2)
except Queue.Empty:
pass
if __name__ == "__main__":
# shared Queue for all the processes
intQueue = multiprocessing.Queue()
# producer - receives ints from the C++ stdout and inserts into Queue
multiprocessing.Process(target=funcA, args=(intQueue,)).start()
# consumer - prints ints from the Queue
multiprocessing.Process(target=funcB, args=(intQueue,)).start()
使用Popen
的communicate
方法,如下所示:
handle = subprocess.Popen(['../C++/C++.exe'], stdout=subprocess.PIPE)
out, err = handle.communicate() # this will block until the underlying subprocess exits
至於隊列,數據結構定義了查詢該隊列是滿還是空的方法。 利用這些。
如果有人遇到同樣的問題:
對於問題 1,當從 handle.stdout.read() 拆分返回的列表長度為 1 時,我使用了 while(1) 中斷(這意味着管道沒有返回任何內容)。
對於問題 2,我使用了這篇文章中描述的毒丸方法: http://www.doughellmann.com/PyMOTW/multiprocessing/communication.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.