2014-09-29 78 views
1
def adbshell(command, serial=None, adbpath='adb'): 
    args = [adbpath] 
    if serial is not None: 
     args.extend(['-s', serial]) 
    args.extend(['shell', command]) 
    return subprocess.check_output(args) 



def pmpath(serial=None, adbpath='adb'): 
    return adbshell('am instrument -e class............', serial=serial, adbpath=adbpath) 

我必須在特定的時間段內運行此測試,然後退出,如果它不工作。我如何提供暫停?Python中的時間管理子流程

回答

1

取決於您運行的是哪個Python版本。

的Python 3.3起:

subprocess.check_output()提供timeout PARAM。檢查簽名here

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None) 

下面的Python 3.3:

可以使用threading模塊。喜歡的東西:

def run(args, timeout): 
    def target(): 
     print 'Start thread' 
     subprocess.check_output(args) 
     print 'End thread' 

    thread = threading.Thread(target=target) 
    thread.start() # Start executing the target() 

    thread.join(timeout) # Join the thread after specified timeout 

注意 - 我沒有測試以上threadingcheck_output()的代碼。通常我使用subprocess.Popen(),它提供了更多的靈活性,可以處理幾乎所有的場景。檢查doc

1

Popen結構提供了更多的靈活性,因爲它可以用來檢查subprocess調用的退出狀態。如果進程尚未終止,則返回None。因此,調用子進程sleep所需的時間。

考慮一個簡單的test.py這是從主程序調用的子進程。

import time 

for i in range(10): 
     print i 
     time.sleep(2) 

test.py從另外一個程序使用subprocess.Popen

from subprocess import Popen, PIPE 
import time 

cmd = Popen(['python','test.py'],stdout=PIPE) 
print cmd.poll() 
time.sleep(2) 
if cmd.poll()== None: 
     print "killing" 
     cmd.terminate() 

time.sleep(2)

提供超時2秒調用,從而使程序能夠excecute。 檢查進程退出狀態使用Popen.poll

如果None,進程沒有終止,殺死進程。