2014-11-22 13 views
1

파이썬을 통해 gnuplot을 실행하려고합니다.파이썬 하위 프로세스 stdout이 읽지 않습니다

명령을 보내고 실행할 수는 있지만 응용 프로그램에서 경고 또는 오류 메시지를 읽을 수는 없습니다. 그냥 여기에서 기다립니다 : "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 :

경고 : 인해 다른 OS 파이프 중 하나에 교착 상태를 피하기 위해 오히려 .stdin.write, .stdout.read 또는 .stderr.read 미만) (연통 버퍼가 자식 프로세스를 채우고 차단합니다.

제안 사항대로 process.communicate()을 사용하고 싶을 것입니다. 이것은 stdout_data, stderr_data의 튜플을 제공하므로 두 번째 경고와 오류를 가져 오십시오. 이것은 출력을 수동으로 읽는 것을 다루어야하는 문제와 이것과 같은 문제를 피할 수 있습니다.