2013-02-20 137 views
0

我希望記錄應用程序(eg.com.clov4r.android.nil)我操作應用程序時的CPU佔用率(例如,執行猴子測試),並完成記錄時,我eixt應用程序(例如,猴子測試)。如何用python實現它?蟒蛇如何保持一個線程執行,直到其他線程完成

有些代碼:

packagename = 'com.clov4r.android.nil' 
cmd1 = 'adb shell top -d 5 | grep com.clov4r.android.nil' 
cmd2 = 'adb shell monkey -v -p com.clov4r.android.nil --throttle 500 --ignore-crashes --ignore-timeouts --ignore-security-exceptions --monitor-native-crashes -s 2345 100' 
t1 = threading.Thread(target=subprocess.call(cmd1, stdout=open(r'123.txt', 'w'))) 
t2 = threading.Thread(target=subprocess.call(cmd2)) 
+3

你能告訴我們你需要修復的代碼嗎? – 2013-02-20 06:00:10

+0

以上是我的代碼,感謝您的關注 – Fern 2013-02-20 06:52:49

回答

0

您可以使用Thread.join()

import threading, time 

def worker(): 
    time.sleep(5) 

t = threading.Thread(target=worker) 
t.start() 
t.join() 
print('finished') 
0

事件是線程之間(http://docs.python.org/2/library/threading.html#event-objects)溝通的好方法。但是,您將遇到的另一個問題是,頂級命令將永遠運行。我會做這樣的事情:

def run_top(event, top_cmd): 
    s = subprocess.Popen(top_cmd, stdout=open('123.txt', 'w')) 
    event.wait() # Wait until event is set, then kill subprocess 
    s.kill() 

def run_monkey(event, monkey_cmd): 
    subprocess.call(monkey_cmd) 
    event.set() # Once we're finished set the event to tell the other thread to exit 

event = threading.Event() 
threading.Thread(target=run_top, args=(event, your_top_command)).start() 
threading.Thread(target=run_monkey, args=(event, your_monkey_command)).start() 

可能有辦法殺死線程,但這是非常醜陋的,這種方式是更加控制。

我也會說run_monkey()不需要在一個線程中運行,但不知道你有什麼其他代碼可能需要它。

+0

謝謝,我已經更新:)。 – Daniel 2013-02-20 08:18:07