Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python子进程stdout不读取_Python_Pipe_Subprocess_Communicate - Fatal编程技术网

Python子进程stdout不读取

Python子进程stdout不读取,python,pipe,subprocess,communicate,Python,Pipe,Subprocess,Communicate,我正在尝试通过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.d

我正在尝试通过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
读取的部分

请注意:

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

您可能希望按照建议使用。这将为您提供一组
stdout\u数据、stderr\u数据
,因此只需抓取第二组即可获得警告和错误。这避免了必须手动读取输出的问题,以及类似的问题