python function terminated,n秒后终止Python中的函数调用

my python code goes like this:

def a():

...

...

subprocess.call()

...

...

def b():

...

...

and so on.

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?

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()

...

...

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.

The back end gcc is of linux.

解决方案

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值