2013-09-24 32 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... 

我只是不知道如何可以得到/路徑/返回代碼/腳本。

也許我只是需要插入邏輯/路徑/到/腳本,任何想法?

感謝,

回答

4

subprocess.Popen對象有一個returncode屬性,您可以訪問:

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

你也可以看看使用check_call方便的功能:

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

它只會返回如果返回碼爲零;否則,它將引發一個CalledProcessError(從中您可能會看到returncode屬性)。

你的榜樣,與輸出和錯誤在調用Python腳本回指向,而不是一個日誌文件:

>>> 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()方法終止。