python中的多线程 [英] Multi-Threading in python

查看:86
本文介绍了python中的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的python代码是这样的:



def a():

...

...

subprocess.call()

...

...



def b():

...

...



等等。



我的任务:

1)如果subprocess.call()在3秒内返回,我的执行应该继续subprocess.call ()返回。

2)如果subprocess.call()在3秒内没有返回,则应该终止subprocess.call()并在3秒后继续执行。

3)在subprocess.call()返回或3秒结束之前,不应该进行进一步的执行。



这可以通过线程完成但是如何完成?





真实代码的相关部分如下:



...

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", 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();



...

...



我正在尝试使用python编译和执行C程序。

当我使用subprocess.call()执行C程序并假设C程序包含无限循环时,则子进程s.call()应该在3秒后终止,程序应该继续。我应该能够知道subprocess.call()是否被强制终止或成功执行,以便我可以在下面的代码中打印消息。


...
...

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.

推荐答案

实现主线程中的某种形式的计时器,用于检查呼叫是否已返回。请参阅 https://docs.python.org/3.3/library/threading.html#module-threading [ ^ ] ,了解更多信息。
Implement some form of timer in your main thread to check whether the call has returned. See https://docs.python.org/3.3/library/threading.html#module-threading[^], for more information.


这篇关于python中的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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