我已经阅读了很多关于使用线程,子进程等的帖子.对于我正在尝试做的事情,很多事情似乎过于复杂......
我想要做的就是在X时间过后停止执行一个函数.
def big_loop(bob):
x = bob
start = time.time()
while True:
print time.time()-start
Run Code Online (Sandbox Code Playgroud)
此函数是一个无限循环,永远不会抛出任何错误或异常,句点.我不确定"命令,shell,子进程,线程等......"和这个函数之间的区别,这就是我在操作子进程时遇到问题的原因.
我在这里找到了这个代码,然后尝试了它,但是你可以看到它在10秒后继续打印:
import time
import threading
import subprocess as sub
import time
class RunCmd(threading.Thread):
def __init__(self, cmd, timeout):
threading.Thread.__init__(self)
self.cmd = cmd
self.timeout = timeout
def run(self):
self.p = sub.Popen(self.cmd)
self.p.wait()
def Run(self):
self.start()
self.join(self.timeout)
if self.is_alive():
self.p.terminate()
self.join()
def big_loop(bob):
x = bob
start = time.time()
while True:
print time.time()-start
RunCmd(big_loop('jimijojo'), 10).Run() #supposed to quit after 10 seconds, but doesn't
x = raw_input('DONEEEEEEEEEEEE')
Run Code Online (Sandbox Code Playgroud)
这个功能被杀死的简单方法是什么.正如你在上面的尝试中所看到的那样,它在20秒后不会终止并继续......
***哦,我也读过有关使用信号的内容,但是我在Windows上,所以我不能使用闹钟功能..(python …
python ×1