[英]Exit an imported module without exiting the main program - Python
我有一個名為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 except 中導入了模塊,但是由於我想在多個模塊上做同樣的事情,我找到了一種方法來以編程方式循環遍歷單個 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.