是否可以在没有 GUI 或 类 的情况下使用 PyQt5 QtSerialPort?

Is it possible to use PyQt5 QtSerialPort without GUI's or classes?

关键是要有只在有东西要读的时候才读的功能,而不是使用没有特殊方法的pyserial。我想这可能会涉及一个更大的问题,即是否可以在没有 GUI 类(从其他对象继承)的情况下使用信号和插槽。我可以让串行端口写入,但不能读取,

from PyQt5 import QtCore, QtSerialPort
serial_port = QtSerialPort.QSerialPort('COM3')
serial_port.open(QtCore.QIODevice.ReadWrite)
serial_port.write(bytes([255]))

def handle_ready_read():
    while serial_port.canReadLine():
        print(serial_port.readAll())
        print('here')
        serial_port.close()

serial_port.readyRead.connect(handle_ready_read)

没有打印出来,即使在使用 pyserial 时读取了一些东西。

您不需要 GUI 来使用 Qt。 Qt中有一个专用的GUI module,不依赖它的东西,不需要GUI。

但是,要使用插槽和信号,您需要 运行 Qt 的事件循环。常规方法是使用 QCoreApplication.

app = QCoreApplication([])

# setup your serial port here

sys.exit(app.exec_())