2017-03-20 10 views
0

subprocess.Popen으로 일부 프로그램을 실행하고 파일에 stdout/stderr을 기록하는 python 서비스가 있습니다. 그것은 대답 here을 기반으로 멋지게 작동합니다.stdout을 subprocess.Popen에서 파일로 안전하게 리디렉션합니다.

서비스로 실행 중이므로 정리가 올바르게 수행되었는지 확인하고 싶습니다.

while RunningService: 
    try: 
     command = "some command to run the program with arguments" 

     with open('out-file.txt', 'a') as f_out: 
      myProc = subprocess.Popen(command, stdout=f_out, stderr=f_out) 

     # some looping/waiting 
     # ... 
     # ... 

     if breakCondition: 
      break 

    except Exception as e: 
     # do some error logging for the caught exception 
    finally: 
     myProc.kill() 

은 내가 이해하고 싶은 것은 우리가 프로세스를 종료 할 때 f_out을 처리하는 파일에 발생하는 것입니다 : 코드는 다음과 유사한 구조를 가지고있다. 파일은 언제 닫습니까? 다른 함수에서 Popen 객체를 생성하고 반환한다면 다른 것입니까?

+0

'with open ... as f_out : '범위를 종료하면'f_out'이 삭제됩니다. –

답변

0

첫째, 그것은 잘못이다, 그리고

myProc = subprocess.Popen(command, stdout=f_out, stderr=subprocess.STDOUT) 

주의 :

myProc = subprocess.Popen(command, stdout=f_out, stderr=f_out) 

당신은 오히려 모두 stdoutstderr하지만 대한 f_out를 사용하지 말아야 프로세스는 with 이상 실행하는 경우 차단 된 파일에 쓰기를 시도 할 수 있으며 예외가 발생합니다.

프로세스는 with 블록 내에서 종료되어야합니다. 종료하거나 완료 할 때까지 myProc.wait() (블로킹) 또는 myProc.poll() is not None (블로킹 없음)

+0

이 경우 프로세스의'stdout'과'stderr'은 여전히'stderr'가'stdout'을 통해 진행하는 것과 같은 파일에 기록됩니까? – dixie

+0

동일한 파일입니다. 직접 해보십시오. –