[英]python popen.stdout.readline() hangs
我遇到了一個問題...有誰知道為什么這段代碼掛在 while 循環中。 循環似乎沒有捕捉到stdout
的最后一行。
working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
line = working_file.stdout.readline()
working_file.stdout.flush()
while working_file != "" :
print(line)
line = working_file.stdout.readline()
working_file.stdout.flush()
當遇到readline()
時,腳本會掛起,光標只會閃爍。 我不明白為什么。 任何人都可以透露一些信息嗎?
進行非阻塞讀取對您有幫助嗎?
import fcntl
import os
def nonBlockReadline(output):
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.readline()
except:
return ''
working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
line = nonBlockReadline(working_file.stdout)
working_file.stdout.flush()
while working_file != "" :
print(line)
line = nonBlockReadline(working_file.stdout)
working_file.stdout.flush()
我不確定你到底想做什么,但這會更好嗎? 它只是讀取所有數據,而不是一次只讀取一行。 它對我來說更具可讀性。
import fcntl
import os
def nonBlockRead(output):
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.read()
except:
return ''
working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = ''
while working_file.poll() is None:
stdout += nonBlockRead(working_file.stdout)
# we can probably save some time and just print it instead...
#print(stdout)
stdout = stdout.splitlines()
for line in stdout:
print(line)
編輯:應該更適合您的用例的通用腳本:
import fcntl
import os
def nonBlockRead(output):
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.read()
except:
return ''
working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
while working_file.poll() is None:
stdout = nonBlockRead(working_file.stdout)
# make sure it returned data
if stdout:
# process data
working_file.stdin.write(something)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.