退出导入的模块而不退出主程序 - Python

use*_*471 6 python exit quit

我有一个名为的模块randomstuff,我将其导入到我的主程序中。问题是,有时需要停止正在运行的代码randomstuff,而不影响主程序。

我尝试过 exit()、quit() 和一些操作系统函数,但它们都想关闭我的主程序。在模块内部,我有一个线程来检查模块是否应该停止 - 那么当它意识到必须停止程序时,我应该在线程中放置什么函数。

关于如何解决这个问题有什么想法吗?谢谢

Mal*_*imi 0

我有一个新的答案,因为我现在知道你的意思了。您必须使用布尔值扩展线程类来存储线程的当前状态,如下所示:

mythread.py

from threading import *
import time

class MyThread(Thread):
    def __init__(self):
        self.running = True
        Thread.__init__(self)

    def stop(self):
        self.running = False

    def run(self):
        while self.running:
            print 'Doing something'
            time.sleep(1.0/60)


thread = MyThread()
thread.start()
Run Code Online (Sandbox Code Playgroud)

mainscript.py

from mythread import *
thread.stop() # omit this line to continue the thread
Run Code Online (Sandbox Code Playgroud)