用python线程终止脚本

2024-09-30 05:21:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些密码:

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

但也不管用。你知道吗


Tags: selfinitdefredthreadclassprintthreading
1条回答
网友
1楼 · 发布于 2024-09-30 05:21:08

这不会解决你的问题,但我会把这个留在这里,以防有人从搜索引擎来寻找结束线程很好的线程实际上仍然活着。你知道吗

class worker(threading.Thread):
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self)

    def run(self):
        main_thread = None
        for thread in threading.enumerate():
            if thread.name == 'MainThread':
                main_thread = thread
                break

        while main_thread and main_thread.isAlive():
            #do_work()
            print('Thread alive')
            time.sleep(1)

# I'll keep some of the analogy from above here:
threads = []
thread = worker()
threads.append(thread)

for f in threads:
    f.start()

time.sleep(5)

for f in threads:
    print('Is thread alive:', f.isAlive())

程序将在~5秒后退出,如果线程仍然活着,则在打印之后立即退出(它们将是),但是这些线程将查找主进程状态并在主线程死亡时终止。你知道吗

这是创建线程的一种方法,该线程将在主程序运行时结束。
在实践中问题更大,你必须确保它们很好地终止,并自己清理它们。还有f.join()等待线程终止,这里可以找到一个很好的解释:what is the use of join() in python threading

还有一个信号告诉线程是时候退出了,这也已经被彻底讨论过了,这里有一个很好的例子:How to stop a looping thread in Python?

这只是一个很小的示例(仍然不完整,但是可以工作),它展示了如何创建在主程序执行时终止的线程的一般要点。你知道吗

相关问题 更多 >

    热门问题