Problems with serial port interface

MRAB python at mrabarnett.plus.com
Fri Jun 7 10:18:17 EDT 2013


On 07/06/2013 11:17, lionelgreenstreet at gmail.com wrote:
> Sorry for my quote,
> but do you have any suggestion?
>
> Il giorno martedì 4 giugno 2013 23:25:21 UTC+2, lionelgr... at gmail.com ha scritto:
>> Hi,
>>
>> i'm programming in python for the first time: i want to create a serial port reader. I'm using python3.3 and pyQT4; i'm using also pyserial.
>>
>> Below a snippet of the code:
>>
>>
>> class CReader(QThread):
>>     def start(self, ser, priority = QThread.InheritPriority):
>>         self.ser = ser
>>         QThread.start(self, priority)
>>         self._isRunning = True
>>         self.numData=0;
>>
>>     def run(self):
>>         print("Enter Creader")
>>         while True:
>>             if self._isRunning:
>>                 try:
>>                     data = self.ser.read(self.numData)
>>                     n = self.ser.inWaiting()
>>                     if n:
>>                         data = self.ser.read(n)
>>                         self.emit(SIGNAL("newData(QString)"), data.decode('cp1252', 'ignore'))
>>                         self.ser.flushInput()
>>                 except:
>>                     pass
>>             else:
>>                 return
>>
>>     def stop(self):
>>         self._isRunning = False
>>         self.wait()
>>
>> This code seems work well, but i have problems in this test case:
>>
>> +baud rate:19200
>> +8/n/1
>> +data transmitted: 1 byte every 5ms
>>
>> After 30seconds (more or less) the program crashes: seems a buffer problem, but i'm not really sure.
>>
>> What's wrong?
>>
Using a "bare except" like this:

try:
     ...
except:
     ...

is virtually always a bad idea. The only time I'd ever do that would
be, say, to catch something, print a message, and then re-raise it:

try:
     ...
except:
     print("Something went wrong!")
     raise

Even then, catching Exception would be better than a bare except. A
bare except will catch _every_ exception, including NameError (which
would mean that it can't find a name, possibly due to a spelling error).

A bare except with pass, like you have, is _never_ a good idea. Python
might be trying to complain about a problem, but you're preventing it
from doing so.

Try removing the try...except: pass and let Python tell you if it has a
problem.



More information about the Python-list mailing list