[英]Python subprocess stdout does not read
我正在嘗試通過python運行gnuplot。
我可以發送和運行命令,但不能從應用程序中讀取警告或錯誤消息。 它只是在這里等待:“ self.proc.stdout.readline()”。
這是我的整個代碼:
from subprocess import PIPE, Popen
import fcntl, os
class Gnuplot:
def __init__(self, debug=True):
self.debug = debug
if self.debug:
print 'Initializing ...\n'
self.proc = Popen(['gnuplot','-persist'],stdin=PIPE, stdout=PIPE, stderr=PIPE)
fcntl.fcntl(self.proc.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
def communicate(self, cin='\n'):
self.proc.stdin.write(cin+'\n')
cout, cerr = '', ''
print "lol"
if self.proc.stdout:
cout = self.proc.stdout.readline()
self.proc.stdout.close()
print cout
elif self.proc.stderr:
cerr = self.proc.stderr.read()
self.proc.stderr.close()
print cerr
if __name__ == '__main__':
g = Gnuplot()
g.communicate("set parameter\n")
g.communicate("plot sin(x)\n")
它只是在這里等待:
cout = self.proc.stdout.readline()
警告和錯誤通常在標准錯誤流上輸出,而不是在標准輸出上輸出(例如,這將阻止結果與警告消息混淆)。 因為您首先從stdout
讀取,並且沒有給出任何輸出,所以您不會到達從stderr
讀取的部分。
注意,該subprocess
建議不要直接訪問流 :
警告:請使用communication()而不是.stdin.write,.stdout.read或.stderr.read來避免死鎖,這是由於其他任何OS管道緩沖區中的任何一個緩沖區填滿並阻塞了子進程。
您可能想要按照建議使用process.communicate()
。 這為您提供了stdout_data, stderr_data
的元組,因此只需抓住第二個即可獲取警告和錯誤。 這回避了必須手動讀取輸出的問題以及類似的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.