【发布时间】:2018-08-11 18:07:37
【问题描述】:
我在做什么:
我正在制作一个 PyQt 应用程序,它允许用户从他们的机器中选择一个脚本文件,然后该应用程序使用 exec() 在单独的 QThread 上执行它,然后向他们显示结果。我已经实现了所有这些,现在我正在尝试添加一个“停止执行”按钮。
问题:
我无法中断脚本执行,只要用户按下“停止执行”按钮,就会发生这种情况。我无法停止正在执行脚本的QObject 的任务或终止托管该对象的QThread。
我的代码:
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import QObject, QThread
class Execute(QObject):
def __init__(self, script):
super().__init__()
self.script = script
def run(self):
exec(open(self.script).read())
class GUI(QMainWindow):
# Lots of irrelevant code here ...
# Called when "Start Executing" button is pressed
def startExecuting(self, user_script):
self.thread = QThread()
self.test = Execute(user_script)
self.test.moveToThread(self.thread)
self.thread.started.connect(self.test.run)
self.thread.start()
# Called when "Stop Executing" button is pressed
def stopExecuting(self):
# Somehow stop script execution
我的尝试:
有很多关于停止exec() 或QThread 的问题,但在我的情况下它们都不起作用。这是我尝试过的:
- 从 GUI 调用
thread.quit()(在脚本执行结束后杀死线程 - 与wait()相同) - 从对象引发
SystemExit(脚本执行结束后退出整个应用程序) - 从 GUI 调用
thread.terminate()(按下“停止执行”按钮时应用程序崩溃) - 使用终止标志变量(不适用于我的情况,因为
run()不是基于循环的)
那么,有没有其他解决方案可以在按下按钮时停止exec() 或立即终止线程?
【问题讨论】:
-
如果任意代码块没有明确提供中断机制,就无法终止它。毕竟,代码可能只是
while True: print('spam')- 这将永远阻塞。多线程在这里是错误的方法 - 您需要使用多处理。 -
@ekhumoro 如果我使用多处理,我可以中断执行吗?
-
是的,你可以直接杀死它,就像你想要一个单独的进程一样。
标签: python python-3.x pyqt pyqt5 qthread