2012-04-15 83 views
2

目前我正在使用python os.system(cmd)來做一些日常工作。python os.system()在命令尚未完成時自動退出

這裏有一種情況,cmd需要5-6分鐘才能完成,而且我運行這個cmd是可以的,但是當我把它放入os.system(cmd)時,os.system(cmd)會在cmd還沒完成時自動退出。

所以我的問題是:如何處理這個問題,設置超時值還是有更好的方法來完成這項工作?

在此先感謝!

+0

是的,謝謝邁克爾。我檢查了這個文檔,沒有找到結果,你能提供一些URL或者一些信息,很多非常感謝 – 2012-04-15 10:08:51

+0

'cmd'字符串是什麼樣的? – Keith 2012-04-15 12:03:27

回答

3

您是否試過subprocess模塊?它被添加以代替os.system以及其他較老的os方法。下面是從文檔幾乎直:

import os 
import subprocess 

proc = subprocess.Popen(cmd, shell=True) 
pid, sts = os.waitpid(proc.pid, 0) 

# you may check on this process later and kill it if it's taking too long 
if proc.poll() in [whatever, ...]: 
    os.kill(proc.pid) 

,或者如果你試圖調試爲什麼進程退出:

import subprocess 
import sys 

try: 
    retcode = subprocess.call(cmd, shell=True) 
    if retcode < 0: 
     print >>sys.stderr, "Child was terminated by signal", -retcode 
    else: 
     print >>sys.stderr, "Child returned", retcode 
except OSError, e: 
    print >>sys.stderr, "Execution failed:", e 
+0

謝謝mVchr,你太快了。我只是在我的環境中嘗試你的方式。有一些問題:1:在我的環境中,返回代碼233,這意味着什麼? 2實際上我在提問中提到過,它是一個shell腳本(* .bin),使用python調用和./***.bin,有沒有什麼不同?非常感謝 – 2012-04-15 10:05:03

+0

1:這不是我所知道的標準shell退出代碼,所以你將不得不諮詢你正在運行的進程... 2:這取決於#你設置了什麼! – mVChr 2012-04-15 16:37:28

相關問題