[英]Python - How to do non-blocking read from PIPE in subprocess.Popen?
我上周發布了類似的問題 ,這篇文章反映了我的審判以及我現在面臨的問題。
通過Popen調用的程序是命令行程序。 我使用一個線程從隊列中讀取一項並將其發送到stdin,並從stdout獲取響應。 但是,它掛在proc.stdout.read()
。 我確實看到它在上周五的預期輸出中運行良好,然后當我今天進行了一些更改時,它掛起了。 我所做的更改是將read()
替換為readlines()
並使用循環來迭代結果。 我知道readlines()
可能會阻塞,但是當我上周五將代碼反轉到read()
所在的位置時,它也會阻塞。 我現在完全迷失了它。 任何可能的原因?
下面是從隊列中獲取一句話並將其饋送到java程序以獲得響應的代碼:
''' below is the code for worker thread. '''
def readQueue(proc, queue):
print 'enter queueThread.\n'
global notEmpty
notEmpty = True
while notEmpty:
try:
sen = queue.get()
proc.stdin.write(sen.strip())
res = proc.stdout.read()
print res.strip(), ' ', sen
queue.task_done()
except Empty:
break
print 'leave queueThread.'
下面的主線程是從文件中讀取每一行,並將其放入隊列中,以便工作線程逐項處理:
def testSubprocess():
ee = open('sentences.txt', 'r')
#ff = open('result.txt', 'w') # print it to stdout first before really write to a file.
lines = ee.readlines()
cmd = ['java',
'-cp', 'someUsefulTools.jar',
'className',
'-stdin',] # take input from stdin
proc = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=PIPE, bufsize=-1, universal_newlines=True)
q = Queue()
for sen in lines:
q.put(sen.strip())
readThread = Thread(target=readQueue, args=(proc, q))
readThread.daemon = True
readThread.start()
print 'Main thread is waiting...\n'
q.join()
global notEmpty; notEmpty = False
print 'Done!'
子流程中的管道是類似於對象的文件。
如果您未指定應讀取的內容,則這些對象上的方法read()
會將所有內容讀取到內存中,直到達到EOF為止,請參見doc: https : //docs.python.org/2/library/stdtypes.html#file .read 。
如果您不希望這種行為,則必須設置要讀取的大小。 嘗試將其設置為1個字節?
readlines()
,請參見文檔: https : //docs.python.org/2/library/stdtypes.html#file.readlines
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.