无法在linux Ubuntu 16.04中的QThread类中运行pyshark.FileCapture(pcap)

2024-06-01 02:03:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个在windows下工作的PySide2应用程序。它所做的是在QThread类中使用python-pyshark库打开一个网络数据包(pcap)文件。它可以打开pcap文件,但当我试图在ubuntu上运行相同的应用程序时,它抛出了一个错误。RuntimeError:无法添加子处理程序,子观察程序没有附加循环

我在网上搜索解决方案,偶然发现了这个网站->https://github.com/KimiNewt/pyshark/issues/303

pyshark似乎只能在主线程中运行,而不能在子线程中运行。 我还创建了一个复制我的问题的最小示例,如下所示

import sys
import pyshark
import asyncio
from PySide2.QtCore import QThread, Qt, Slot
from PySide2.QtWidgets import QApplication, QMainWindow, QFrame, QHBoxLayout, QPushButton


class SubThread(QThread):
    def __init__(self):
        super(SubThread, self).__init__()
        self.Input_file = "profibus.pcap"

    def run(self):
        print("thread is running!")
        cap = pyshark.FileCapture(self.Input_file)
        iter_obj = iter(cap)
        pkt = next(iter_obj)
        print(pkt)
        cap.close()

class TopLayout(QFrame):
    def __init__(self, sub_thread):
        self.frame = QFrame()
        self.layout = QHBoxLayout()
        self.sub_thread = sub_thread

        self.toggle_button_box = QHBoxLayout()
        self.toggle_button = QPushButton("Start")
        self.toggle_button.setCheckable(True)
        self.toggle_button_box.addWidget(self.toggle_button)

        self.layout.addLayout(self.toggle_button_box)
        self.layout.setAlignment(Qt.AlignCenter)

        self.frame.setLayout(self.layout)
        self.toggle_button.clicked.connect(self.on_toggle_button_clicked)



    @Slot()
    def on_toggle_button_clicked(self):
        self.sub_thread.start()


class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.SubThread = SubThread()
        self.top_layout = TopLayout(self.SubThread)

        self.setCentralWidget(self.top_layout.frame)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    # Execute application
    sys.exit(app.exec_())


我当前的环境配置为:

  • Python 3.7
  • Pyside2 5.13.2
  • Pyshark 0.4.2.9(最新版本)

Tags: importselfinitdefsyspcapbuttonthread