2014-11-22 57 views
1

我想通过python运行gnuplot。Python子进程标准输出不读取

我可以发送和运行命令,但无法读取应用程序中的警告或错误消息。它只是在这里等待:“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

警告和错误通常在标准错误流,而不是标准输出输出(此站结果得到混合例如警告消息)。由于您首先从stdout开始读取,并且没有输出结果,因此您没有进入从stderr读取的部分。

。注意,subprocess recommends against accessing the streams directly

警告:通信(),而不是.stdin.write,.stdout.read或 .stderr.read避免死锁由于任何其他OS管 的填充和阻止子进程的缓冲区。

您可能想按照建议使用process.communicate()。这给了你一个stdout_data, stderr_data的元组,所以只需抓住第二个来获得你的警告和错误。这避免了不得不处理手动读取输出的问题,以及这样的问题。

相关问题