2014-11-22 84 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的元組,所以只需抓住第二個來獲得你的警告和錯誤。這避免了不得不處理手動讀取輸出的問題,以及這樣的問題。

相關問題