【问题标题】:Exit an imported module without exiting the main program - Python退出导入的模块而不退出主程序 - Python
【发布时间】:2015-03-20 06:01:21
【问题描述】:

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

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

关于如何解决这个问题的任何想法? 谢谢

【问题讨论】:

标签: python exit quit


【解决方案1】:

基本上我在 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()

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 抱歉补充回复了,不过我刚刚有时间测试了一下,好像不行。我使用了你的确切代码,除了在 mainscript.py 中添加了 100ms 的延迟,在导入线程和停止它之间。
    • 它在我的电脑上运行良好。线程在一个文件中初始化,在另一个文件中导入和停止。
    • 尝试省略thread.stop(),你会看到它会连续打印。
    • 是的,如果我省略 thread.stop(),它会持续工作。但是,如果我放入 thread.stop(),它不会停止线程。
    • 对我来说效果很好,打印一次然后线程停止。尝试在 IDLE 中运行。
    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多