在 Python 中超时子进程


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 版本。

Python 3.3 及更高版本:

subprocess.check_output()提供了一个timeout参数。在此处检查签名

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()它提供了更大的灵活性并处理几乎所有场景。查看文档

Popen结构提供了更大的灵活性,因为它可用于检查subprocess调用的退出状态。

如果进程尚未终止,则Popen.poll返回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 秒的超时,以便程序可以超过。使用 Popen.poll 检查进程的退出状态

如果None,则进程尚未终止,则终止进程。

最新更新