我有一个名为randomstuff
的模块,我将其导入到主程序中。问题是有时需要停止在randomstuff
中运行的代码,而不影响主程序。
我已经尝试过exit(),quit()和一些os函数,但是所有这些函数也都希望关闭我的主程序。在模块内部,我有一个线程检查该模块是否应该停止-因此,当它意识到必须停止该程序时,应该在该线程中放置什么函数。
关于如何进行此操作的任何想法?谢谢
我有一个新答案,因为我现在知道您的意思。您必须使用布尔值扩展线程类以存储线程的当前状态,如下所示:
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()
mainscript.py
from mythread import *
thread.stop() # omit this line to continue the thread
[基本上,我在try除外中导入了模块,但是由于我想对多个模块执行相同的操作,所以我找到了一种方法,可以通过编程方式在单个try-except中循环遍历模块,然后继续。
从主程序:
import importlib
importList = ['module1','module2']
for lib in importList:
try:
print('Importing %s' % lib)
globals()[lib] = importlib.import_module(lib)
except SystemExit:
continue
从模块线程:
sys.exit()