【发布时间】:2019-04-13 18:15:30
【问题描述】:
我有一些代码:
red = "\033[1;31m"
green = "\033[1;32m"
yellow = "\033[1;33m"
blue = "\033[1;34m"
defaultcolor = "\033[0m"
class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
x=1
def timer(stopon):
timertime = 0
while True:
time.sleep(1)
timertime += 1
print timertime
if timertime == stopon:
killpro()
def killpro():
sys.exit()
threadsyy = []
threadsamount = 300
i = 1
while i <= threadsamount:
thread = watek()
threadsyy.append(thread)
i += 1
print(yellow + "Thread number" + defaultcolor + ": " + red + str(i) + yellow + " created." + '\n')
a = 0
for f in threadsyy:
f.start()
a += 1
#print "Thread work " + str(a)
timer(5)
我需要在 5 秒后终止 scipt。我尝试使用sys.exit 并使用psutil 终止进程。有谁知道如何终止它?我正在尝试:
class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._kill = threading.Event()
并使用
watek.kill()
但它也不起作用。
【问题讨论】:
-
不确定问题出在哪里,当您执行
x=1时,一旦x变为1,您的线程就会终止。没有什么东西可以让线程保持活力。尝试在您的 for 循环中执行f.isAlive(),您会看到线程已死?此外,没有必要用python-3和python-2标记这篇文章,它们都与python使用相同的标记 - 这意味着它们会得到相同的关注,它只是帮助我们澄清我们使用哪种类型的代码'正在看/两个不同版本带来的挑战。因为你在做print timertime,它表示Python2,所以我删除了python-3。 -
请注意,仅将事件添加到您的 Thread 对象不会做任何有用的事情。线程中执行的代码必须实际检查并响应这样的终止标志。
标签: python python-2.7