n秒后终止Python中的函数调用 [英] terminating a function call in python after n seconds

查看:299
本文介绍了n秒后终止Python中的函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Python code是这样的:

my python code goes like this:

def a():
    ...  
    ...  
    subprocess.call()  
    ...  
    ...  

def b():  
    ...  
    ...  

和等。

我的任务:结果
1)如果 subprocess.call() 3秒内的回报,我的执行应该继续此刻 subprocess.call()回报。结果
2)如果 subprocess.call() 3秒内没有返回,在 subprocess.call()应终止而我的执行应该在3秒后继续进行。结果
3)在 subprocess.call()收益或3秒结束时,进一步执行应该不会发生。

My task:
1) If subprocess.call() returns within 3 seconds, my execution should continue the moment subprocess.call() returns.
2) If subprocess.call() does not return within 3 seconds, the subprocess.call() should be terminated and my execution should continue after 3 seconds.
3) Until subprocess.call() returns or 3 seconds finishes, the further execution should not take place.

这可以与线程,但怎么做?

This can be done with threads but how?

真正的code的有关部分是这样的:

Relevant part of the real code goes like this:

...  
cmd = ["gcc", "-O2", srcname, "-o", execname];    
p = subprocess.Popen(cmd,stderr=errfile)//compiling C program  
...  
...  
inputfile=open(input,'w')  
inputfile.write(scanf_elements)  
inputfile.close()  
inputfile=open(input,'r')  
tempfile=open(temp,'w')
subprocess.call(["./"+execname,str(commandline_argument)],stdin=inputfile,stdout=tempfile); //executing C program
tempfile.close()
inputfile.close()  
...  
...  

我试图编译和使用python执行C程序。
当我使用subprocess.call执行C程序(),并假设如果C程序包含一个无限循环,那么subprocess.call()应在3秒后终止该程序应继续下去。我应该能够知道subprocess.call()是否被强制终止或执行成功,这样我可以在相应以下code打印信息。

I am trying to compile and execute a C program using python. When I am executing C program using subprocess.call() and suppose if the C program contains an infinite loop, then the subprocess.call() should be terminated after 3 seconds and the program should continue. I should be able to know whether the subprocess.call() was forcefully terminated or successfully executed so that I can accordingly print the message in the following code.

后端的gcc是Linux的。

The back end gcc is of linux.

推荐答案

最后,低于code的工作:

Finally the below code worked:

import subprocess
import threading
import time


def process_tree_kill(process_pid):
    subprocess.call(['taskkill', '/F', '/T', '/PID', process_pid])

def main():
    cmd = ["gcc", "-O2", "a.c", "-o", "a"];  
    p = subprocess.Popen(cmd)
    p.wait()
    print "Compiled"
    start = time.time()

    process = subprocess.Popen("a",shell=True)
    print(str(process.pid))   

    # terminate process in timeout seconds
    timeout = 3 # seconds
    timer = threading.Timer(timeout, process_tree_kill,[str(process.pid)])
    timer.start()

    process.wait()
    timer.cancel()

    elapsed = (time.time() - start)
    print elapsed

if __name__=="__main__":
    main()

这篇关于n秒后终止Python中的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆