[英]How to debug PyQt5 threads in Visual Studio Code?
我现在正在开发一个 PyQT5 应用程序,并使用多线程来避免 GUI 冻结。 不幸的是,Visual Studio Code 调试器不会在执行线程内的断点处停止。 我尝试了下一页中的所有建议,但没有解决问题。 https://github.com/microsoft/ptvsd/issues/428 。 我认为 VS Code 将调试器从 ptvsd 切换到 debugpy,因此所有建议都不再适用。 也许有人知道如何解决这个问题。
import time
import sys
from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QApplication, QPushButton, QTextEdit, QVBoxLayout, QWidget, QLabel
class Worker(QObject):
sig_msg = pyqtSignal(str) # message to be shown to user
def __init__(self):
super().__init__()
@pyqtSlot()
def work(self):
self.sig_msg.emit('Hello from inside the thread!')
result = 1 + 1
result2 = 1 + 2
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Thread Example")
form_layout = QVBoxLayout()
self.setLayout(form_layout)
self.resize(400, 200)
self.button_start_threads = QPushButton("Start")
self.button_start_threads.clicked.connect(self.start_threads)
self.label = QLabel()
form_layout.addWidget(self.label)
form_layout.addWidget(self.button_start_threads)
QThread.currentThread().setObjectName('main')
self.__threads = None
def start_threads(self):
self.__threads = []
worker = Worker()
thread = QThread()
thread.setObjectName('thread')
self.__threads.append((thread, worker)) # need to store worker too otherwise will be gc'd
worker.moveToThread(thread)
worker.sig_msg.connect(self.label.setText)
thread.started.connect(worker.work)
thread.start()
if __name__ == "__main__":
app = QApplication([])
form = MyWidget()
form.show()
sys.exit(app.exec_())
您可以通过在 self.sig_msg.emit('Hello from inside the thrad!') 处设置断点来重现错误,在我的情况下,调试器不会在此位置停止。 我使用 VS Code 版本 1.65.2。 代码取自上述帖子。
我最近在 VS Code 和 PyQt5 上遇到了同样的问题。 按照https://code.visualstudio.com/docs/python/debugging#_troubleshooting的建议,我能够通过导入debugpy
并在工作方法中添加debugpy.debug_this_thread()
来在您的示例代码中打断点,例如
def work(self):
debugpy.debug_this_thread()
self.sig_msg.emit('Hello from inside the thread!')
result = 1 + 1
result2 = 1 + 2
希望这可以帮助其他面临同样问题的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.