python - 如何在后台运行无限循环并停止它?

标签 python multithreading python-2.7 tkinter

这是我的问题:使用 Tkinter,我想单击一个按钮并启动一个 python 脚本。 这个 python 脚本现在是一个模块(我不知道这是否是最好的方法)导入到我的主脚本中。 该脚本应该在后台运行。它有一个方法可以退出它。我怎么调用它? 我想向模块传递一个标志或其他东西,但我不知道该怎么做。

现在,我这样调用我的代码:在 gui.py 中

import sniffer_wideband_v09
from Tkinter import *
root = Tk()
def handle_click():
    global t
    global stop_flag
    stop_flag = 0

    def callback():
        sniffer_wideband_v09.main(sampling_rates, center_frequencies, gains, file_dir, files_names) 
    t = Thread(target=callback)
    t.start()
root.mainloop()

我想调用 sniffer_wideband_v09.py 中的 quitting() 方法。或者将标志传递给我的模块以停止无限循环。 之后,我需要将所有这些绑定(bind)到 Tkinter 按钮。

我对这个问题做了一些研究,发现:

Is there any way to kill a Thread in Python? 随着 How to run a function in the background of tkinterHow to run and stop an infinite loop in a python thread

第一个很有前途,但我没有完全理解它,我正在努力。

注意:我直接从我的 shell 使用 ./gui.py 运行它,我在 Ubuntu 下,而不是在 Windows 下。(我认为它可以改变一些处理多线程的方式)。

感谢阅读,任何提示或帮助将不胜感激。如果我同时找到回复,我会发布我的代码。

编辑:提供有关线程中启动的脚本的更多信息:(这是一个 GNURadio 脚本)

class foo():
    def __init__(self):
         self.parameters()
    def methods():
         self.dostuff()
def main(sampling_rates, center_frequencies, gains, file_dir, files_names):
    tb = foo()
    while True: #flag could be here to exit the infinite while.
         tb.start()
    tb.stop()
def quitting():
    tb.stop()
 ## not mandatory piece of code from now on
if __name = "__main__":
     main()
     quitting()

最佳答案

因为你的 Tkinter gui 应用程序和主程序之间没有交互 你从 sniffer_wideband_09 模块调用的代码我会推荐你 使用多处理:

import sniffer_wideband_v09
import multiprocessing
from Tkinter import *
root = Tk()
def handle_click():
    global t

    t = multiprocessing.Process(target=sniffer_wideband_v09.main, args=(sampling_rates, center_frequencies, gains, file_dir, files_names))
    t.start()
root.mainloop()

当你想停止这个过程时,只需调用t.terminate()。阅读有关多处理模块文档的更多信息。

关于python - 如何在后台运行无限循环并停止它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25010780/

相关文章:

python - Flask: orjson 代替 json 模块进行解码

python - 如何在键不一致的字典列表中查找值

java - 更改线程中的 JButton 颜色

python tkinter接口(interface)如何创建一个新的显示txt文件

Python2.7 执行作为命令解析 Unicode 字符串给出的语句不正确,但交互式提示做得很好

python - 如何在 Jupyter Notebook 中输入数据

Java - 如何检查 ServerSocket.accept() 是否连接?

c# - 结合 Interlocked.Increment 和 Interlocked.Exchange

python-2.7 - 使用 Python 删除现有 Excel 工作表中的整个空白行

python - 在 Python 中 object() 和 class myClass(object) 之间 __dict__ 的区别