views:

99

answers:

1

Hello,

I am writing a program that opens and records data sent through a serial port into a text file. I am currently adding functionality to allow reconfiguring the serial port during run-time. I prompt the user to choose which variable to change one at a time, so as to keep it simple for myself (i would appreciate elegant solutions as well).

The pyserial function that creates the serial instance (serial.Serial()) has the following parameters:

import serial
ser = serial.Serial(port=0, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0, writeTimeout=None, dsrdtr=None, interCharTimeout=None) #default values shown

I notice that while most are int() arguments, some are not, i.e. "timeout".

I know using int(raw_input("for the int() type variables)) would let me safely assign the int variables, but the variables with None as default would require an input() function to properly assign the possible None value.

I have read elsewhere that input() is generally not recommended, since it has potential for being exploited(something about eval()?). How then should i handle those inputs? i.e. using serial.Serial() where writeTimout = str(None) throws an error.

Thanks!

A: 

The safest way is just to accept the user's input as a string and then parse it. I.e. let the user enter key=value pairs:

baudrate = 9600
parity = N

Then parse these pairs, by splitting on '=' and stripping both sides. Assign the variables with a string lookup table (the baudrate string maps to the baudrate var, and so on). This way you can handle the None value any way you want.

This method is simple and safe. input will raise exceptions if the user input isn't valid Python, and you may not want that.

Eli Bendersky
I see, I will try that right now. Is it a better idea to have a text file with the two columns of the lookup table(i.e. a dictionary?) or should I just have it initialized when the program runs? Thanks for your time
PPTim
@PPTim: if you're talking about a configuration file that's read by the program, use some of Python's existing options like ConfigParser
Eli Bendersky