我正在尝试通过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()
答案 0 :(得分:0)
警告和错误通常在标准错误流而不是标准输出上输出(例如,这会阻止结果与警告消息混淆)。因为您首先从stdout
开始阅读,并且没有给出输出,所以您无法进入从stderr
读取的部分。
注意,subprocess
recommends against accessing the streams directly:
警告:使用communic()而不是.stdin.write,.stdout.read或 .stderr.read以避免由于任何其他OS管道导致的死锁 缓冲填充和阻止子进程。
您可能希望按照建议使用process.communicate()
。这会给你一个stdout_data, stderr_data
的元组,所以只需抓住第二个来获取警告和错误。这避免了必须处理手动读取输出的问题以及类似的问题。