Sometimes I do not get any data in via the serial interface and I want to catch this case with an exception in the following way:
ser = serial.Serial(3)
ser.baudrate = 115200
timeout = 1
while (some condidion)
try:
dump = ser.read(40)
except ser1.SerialTimeoutException:
print('Data could not be read')
ser.close()
However, when I run this program, the exception is never caught when no
data is in the buffer and I am stuck in an endless loop. Anyone an idea
what I am doing wrong here?
I didn't even know about that exception. After having a look at the API documentation, you'll see that this exception only applies to write().
If you read(), you'll just have a shortened or even empty output.
And this applies only if you have opened the connection with a timeout. Something like serial.Serial(3, timeout=.1).
Related
I learned how to add error handling. But I am little bit confused about when we need to add it to my code.
See this following example.
Do I need error handling for every line of calling the socket?
Server.py
import socket
sockfd = socket.socket()
try:
sockfd.bind(("127.0.0.1", 20001))
except socket.error as emsg:
print("Socket bind error: ", emsg)
sys.exit(1)
print("I_am", socket.gethostname(), "and_I_am_listening_...")
sockfd.listen(5)
new, who = sockfd.accept() # Return the TCP connection
print("A_connection_with", who, "has_been_established")
try:
message = new.recv(50)
except socket.error as err:
print("Recv error: ", err)
if message:
print("\'"+message.decode("ascii")+"\'", "is received from", who)
else:
print("Connection is broken")
new.close()
sockfd.close()
One commonly used approach to error handling is to add it when there is a possibility for something unexpected to happen, i.e. something that you did not expect when writing the code. This means that if you have e.g. a simple function whose different possible error states you know, that is when you do not need to add try-statements since you can handle the errors with e.g. if-else statements. This also usually reduces memory consumption, since try-block has a bigger overhead. But in case there are things that you do not know or have no control over, e.g. external program returns or API calls, that is when you should add error handling.
I wonder if the below python code (specifically http server) ever crashes? Assuming that there is no grammer error in any of the library code(already compiled), what I think that handling the exceptions in a while loop should be sufficient for this code not to crash anytime. I tried the below code for a while and never crashed, but I wonder if theoretically or practically possible for this program to crash?
while True:
try:
server = HTTPServer(('', PORT_NUMBER), myHandler)
server.serve_forever()
except:
try:
server.socket.close()
except:
pass
The actual reason I am asking this question that I don't want to deal with UNIX staff to watch the process and restart it if it crashes. Is the above solution sufficient?
Thanks.
If "except" block has worng code, it can crash cause of it. I mean, something like that:
# path/to/py3
FOO = [1,2,3]
try:
# index out of bound, try block has error, so it goes ahead and executes except-block
print(FOO[4])
except:
# if there is some kind of error, like Syntax error, program can crash
print "Index out of bound!"
print("2"+2)
print(FOO["BAR"])
but if exception block has the correct logic too, then programm should work without crashing
Like Klaus D. already mentioned in his comment, there can be cases where the socket close code in your except block crashes. You could optionally also throw a try except around that as well...
Another option is to use something like this (no UNIX involved):
http://supervisord.org/
It's easy to run and will automatically restart your program if it crashes.
I am very new to python but little experienced with C Programming. I am trying to open and use multiple serial ports using pyserial library, and want to use array of serial ports to keep track of them for read and write operations, Below is my code:
try:
ser[0] = serial.Serial(
SERIAL_COM[0],
baudrate = SERIAL_BAUD_RATE,
timeout = SERIAL_TIMEOUT
)
except:
print ("Exception occurred")
Above code always go into exception, However if i don't use as array i.e. changed ser[0] to ser I don't face exception. I just want to know how can i use serial port array to avoid exception ?
I figured it out myself, i was messing up with arrays previously. Following code is working fine now:
ser = []
ser.append(serial.Serial(
'COM1',
baudrate = SERIAL_BAUD_RATE,
timeout = SERIAL_TIMEOUT
))
If i need to add another port, i will just call ser.append() and port can be accessed through identifier ser[i].
You should not catch all exceptions per se. Instead catch specific ones... But for starters remove the try/except and try again. This will give you/us the actual error message.
I'm trying to use hardware serial port devices with Python, but I'm having timing issues. If I send an interrogation command to the device, it should respond with data. If I try to read the incoming data too quickly, it receives nothing.
import serial
device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0)
device.flushInput()
device.write("command")
response = device.readline()
print response
''
The readline() command isn't blocking and waiting for a new line as it should. Is there a simple workaround?
readline() uses the same timeout value you passed to serial.Serial().
If you want readline to be blocking, just delete the timeout argument, the default value is None.
You could also set it to None before calling readline(), if you want to have a timeout for openening the device:
import serial
try:
device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0.5)
except:
#Exception handeling
device.flushInput()
device.write("command")
device.timeout=None
response = device.readline()
print response
I couldn't add a commend so I will just add this as an answer. You can reference this stackoverflow thread. Someone attempted something similar to your question.
Seems they put their data reading in a loop and continuously looped over it while data came in. You have to ask yourself one thing if you will take this approach, when will you stop collecting data and jump out of the loop? You can try and continue to read data, when you are already collecting, if nothing has come in for a few milliseconds, jump out and take that data and do what you want with it.
You can also try something like:
While True:
serial.flushInput()
serial.write(command)
incommingBYTES = serial.inWaiting()
serial.read(incommingBYTES)
#rest of the code down here
I built a shell python code. It uses common sockets for connections.
If the connection fails, it prints a huge stacktrace.
I would like to take it out by adding something in the script.
The stacktrace tells you where the exception occurs.
If you can do something about it and recover from the error, you could try catching the exception, and handling it yourself.
try:
#line causing stacktrace
except ExceptionType, exception:
#do something with exception