2013-02-20 139 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