Python 子进程标准输出不读取



我正在尝试通过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 parametern")
    g.communicate("plot sin(x)n")     

它只是在这里等待:

cout = self.proc.stdout.readline()

警告和错误通常输出在标准错误流而不是标准输出上(例如,这可以防止结果与警告消息混淆)。因为您首先从stdout读取,并且没有给出输出,所以您不会到达从stderr读取的部分。

请注意,subprocess建议不要直接访问流:

警告:使用 communication() 而不是 .stdin.write、.stdout.read 或 .stderr.read 以避免由于任何其他操作系统管道而导致的死锁 缓冲区填满并阻止子进程。

您可能希望按照建议使用process.communicate()。这给了你一个 stdout_data, stderr_data 元组,所以只需抓住第二个来获取你的警告和错误。这回避了必须手动读取输出的问题,以及类似的问题。

最新更新