python如何保持一个线程执行到另一个线程完成

2024-10-02 00:20:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望录制应用程序(例如:com.clov4r.安卓.nil)我操作应用程序时的CPU占用率(做某事monkey test)并在我进入应用程序时完成录制(整理猴子试验)。如何用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))

Tags: com应用程序targetshellthreadmonkeyandroidignore
2条回答

您可以使用Thread.join()

import threading, time

def worker():
    time.sleep(5)

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

事件是线程(http://docs.python.org/2/library/threading.html#event-objects)之间通信的好方法。但是,另一个问题是top命令实际上将永远运行。我会这样做:

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()不需要在线程中运行,但不确定您还有哪些代码需要它。在

相关问题 更多 >

    热门问题