INTRODUCTION
I am an absolute beginner in Python and I am writing a program that reads the output of a scale and shows it in real-time in a widget. I am using QTextStream with PySide and Python 2.7.14.
PROBLEM DESCRIPTION
The basic program listens to the USB port /dev/ttyUSB0, at baud rate 9600 and shows the value reading from the scale KERN PCB 100-3. The scale is connected through the RS232/USB converter to the PC and is set to AU PC so the weighing values are sent automatically and continuously. So far the program only displays the values in the console. The code:
#!/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
I found a similar thread on using QTextStream with stdin and modified to my need. The code:
#!/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_())
Running the program the console shows the real-time print()
statement together with the message QIODevice::read: WriteOnly device
and changing the OpenModeFlag
to ReadOnly
it gives only the first reading.
QUESTION
The widget it does not display the console output at all. Where is the problem?