2013-09-24 2 views
1

나는 다음과 같은 코드가 있습니다파이썬 하위 프로세스는 popen nohup을 반환 코드

argpass = ['nohup'] 
    argpass.append('/path/to/script') 

    log_output_err = open(log_file,'a+') 
    out = subprocess.Popen(argpass, 
         stdout = log_output_err, 
         stderr = log_output_err) 

    #if the script fails I need to have some logic here... 

난 그냥에/스크립트/경로의 리턴 코드를/얻을 수있는 방법 궁금합니다.

아마도/path/to/script에 논리를 삽입해야 할 필요가 있습니다. subprocess.Popen 객체가 returncode을 가지고

답변

4

덕분에 액세스 할 수있는 속성 :

http://docs.python.org/2/library/subprocess.html#subprocess.Popen.returncode

당신은 또한 check_call 편리한 기능을 사용하여 볼 수 있었다 :

http://docs.python.org/2/library/subprocess.html#subprocess.check_call

을 그것은 단지 돌려 보낼 것이다 반환 코드가 0 인 경우 그렇지 않은 경우 CalledProcessError가 발생합니다 (여기서부터 returncode 속성을 읽을 수 있음).

귀하의 예를 들어, 표준 출력 및 표준 오류 로그 파일이 아닌 호출 파이썬 스크립트를 다시 가리키는 : 프로세스를 완료하는 데 시간이 오래 걸릴 경우

>>> import subprocess 
>>> argpass = ['echo'] 
>>> argpass.append('hello world') 
>>> # I reroute to PIPE because I don't have a logfile 
>>> log_output_err = subprocess.PIPE 
>>> out = subprocess.Popen(argpass, 
       stdout = log_output_err, 
       stderr = log_output_err) 
>>> output,error = out.communicate() 
>>> print output 
hello world 

>>> # Check if child process has terminated. 
>>> # If it has finished, will return returncode attribute. 
>>> # Otherwise, it returns None 
>>> out.poll() 
0 
>>> # Or we can read the returncode attribute directly: 
>>> out.returncode # Direct 
0 
>>> 

returncode 값이 설정되지 않을 수 있습니다 너는 그것을 확인하기 위해 간다. returncode의 값이 None이면 자녀 프로세스가 아직 종료되지 않았 음을 의미합니다. 자식 프로세스가 .wait() 메서드로 종료 될 때까지 스크립트 실행을 중지 할 수 있습니다.

관련 문제