引言
我是Python的绝对初学者,我正在编写一个读取的程序 缩放的输出并在窗口小部件中实时显示。我正在使用QTextStream和PySide以及Python 2.7.14。
问题描述
基本程序以波特率9600监听USB端口/ dev / ttyUSB0,并显示从KERN PCB 100-3刻度读取的值。秤通过RS232 / USB转换器连接到PC并设置为AU PC,因此称量值会自动连续发送。到目前为止,程序仅在控制台中显示值。代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import serial
# define variables
global valueScale, unitScale, replyScale
# open scale port
scale_port = serial.Serial("/dev/ttyUSB0", 9600)
# read usb port
while True:
if (scale_port.inWaiting() > 0):
replyScale = scale_port.read(18)
valueScale = float(replyScale[3:12])
unitScale = replyScale[13]
print valueScale, unitScale
我在使用QTextStream with stdin时发现了一个类似的主题并根据我的需要进行了修改。代码:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from PySide.QtGui import *
from PySide.QtCore import *
import sys
import serial
# open scale port
scale_port = serial.Serial("/dev/ttyUSB0", 9600)
class Widget(QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.setupUi()
self.setupButtonSlots()
self.setupStreams()
def setupUi(self):
self.setLayout(QVBoxLayout())
self.pbReadQt = QPushButton("Read console (using QTextstream)", self)
self.labelReadQt = QLabel('Console output: ', self)
self.layout().addWidget(self.pbReadQt)
self.layout().addWidget(self.labelReadQt)
def setupButtonSlots(self):
self.pbReadQt.clicked.connect(self.readQt)
def setupStreams(self):
self.stdin = QFile()
self.stdin.open(0, QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))
self.stdout = QFile()
self.stdout.open(1, QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly)) # orginal WriteOnly
self.inStream = QTextStream(self.stdin)
self.outStream = QTextStream(self.stdout)
def readQt(self):
global valueScale, unitScale, replyScale
while True:
if (scale_port.inWaiting() > 0):
replyScale = scale_port.read(18)
valueScale = float(replyScale[3:12])
unitScale = replyScale[13]
print valueScale
txt = self.outStream.readLine()
self.labelReadQt.setText('Scale output: %s' % txt)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
运行程序时,控制台会显示实时print()
语句以及消息QIODevice::read: WriteOnly device
,并将OpenModeFlag
更改为ReadOnly
,只会给出第一个读数。
问题
小部件根本不显示控制台输出。问题在哪里?