簡體   English   中英

如何在 Visual Studio Code 中調試 PyQt5 線程?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM