Python运行特定tim的子进程

2024-03-28 23:50:35 发布

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

我正在测试某个exe文件,我想实现一种方法,让我的脚本确定它已经进入了一个无限循环。 这是我当前的代码:

import subprocess
import os
import sys
runs = 1000 # Default run is 1000
if len(sys.argv)>1: # If I want to change the num of runs
    runs = int(sys.argv[1])
FNULL = open(os.devnull, 'w')
logfile = open('logfile', 'w')
args = "exe" # Exe to test
succ = 0
fail = 0
for i in range (0,runs):
    if subprocess.call(args,stdout = logfile, stderr = FNULL) == 100:
        succ += 1 # If returned 100 then success
    else:
        fail += 1 # Else Failed
        break # Break on failure
    open('logfile', 'w').close() # Empties the file
print "Succ: %d , Fail: %d" % (succ, fail)

假设我定义了一个无限循环作为我的exe运行超过5秒。 我该如何实施这一点? 感谢您的帮助,包括关于当前代码的提示!在


Tags: to代码importifossysrunsopen
3条回答

在python3.3中,timeout被添加到subprocess.call. 如果您使用的是python3.3,那么您只需更改subprocess.call将超时作为参数:

   subprocess.call(args,stdout = logfile, stderr = FNULL, timeout=5)

如果您使用的是python2.7,您可以使用subprocess32包,或者需要编写一些额外的代码来处理超时。

如果安装subprocess32模块,则可以使用上述方法subprocess.call以超时为参数。

否则,此代码可以帮助您实现相同的功能:

^{pr2}$

启动一个threading.Timer,它将在5秒后终止进程并报告该操作已完成。您将需要在不同的步骤中创建并等待进程,因此使用Popen对象而不是call。我创建了一个测试程序,用睡眠来模拟你的无限列表。

import subprocess
import os
import sys
import threading

def on_timeout(proc, status_dict):
    """Kill process on timeout and note as status_dict['timeout']=True"""
    # a container used to pass status back to calling thread
    status_dict['timeout'] = True
    print("timed out")
    proc.kill()

runs = 1000 # Default run is 1000
if len(sys.argv)>1: # If I want to change the num of runs
    runs = int(sys.argv[1])
FNULL = open(os.devnull, 'w')
logfile = open('logfile', 'w')
# replacing example with a running program. This is a simple python
# we can call from the command line.
# args = "exe" # Exe to test
test_script = "import time;import sys;time.sleep(%d);sys.exit(100)"
succ = 0
fail = 0
for i in range (0,runs):
    # set by timer 
    status_dict = {'timeout':False}
    # test prog sleeps i seconds
    args = ["python", "-c", test_script % i]
    proc = subprocess.Popen(args, 
        stdout = logfile, stderr = FNULL)
    # trigger timout and kill process in 5 seconds
    timer = threading.Timer(5, on_timeout, (proc, status_dict))
    timer.start()
    proc.wait()
    # in case we didn't hit timeout
    timer.cancel()
    print status_dict
    if not status_dict['timeout'] and proc.returncode == 100:
        succ += 1 # If returned 100 then success
    else:
        fail += 1 # Else Failed
        break # Break on failure
    open('logfile', 'w').close() # Empties the file
print "Succ: %d , Fail: %d" % (succ, fail)

这对我有用

import subprocess
import time

for _ in range(999999): # or whatever
    p1 = subprocess.Popen(['exe_file', 'arg1', 'arg2'])
    time.sleep(0.1)  # wait a small amount of time, hopefully the process ends fast
    return_code = p1.poll()

    if return_code is not None: # we're happy, the process ended fast
        ... # do something to celebrate
    else:  # we're sad. let the process run for at most 5 seconds
        time.sleep(5)   
        p1.terminate()    # this kills the process. try p1.kill() too...
        p1.wait()   #  this cleans up the process registry.

免责声明:这是linux代码。windows上的情况可能有所不同,但您可以先检查一下,然后在这里阅读https://docs.python.org/2/library/subprocess.html关于子进程库以及linux和windows之间的区别的内容。

相关问题 更多 >