There are a lot of great answers on how to read from stdin
in python, but I just can't find anything about reading single characters instead of whole lines. Let me explain:
I need to read information send by an arduino on a serial port, which is forwarded to stdin. This information is processed and stored in a text file. I wrote the programm on the arduino, so I could change how the information is send. The plan was to send the information with an start- (<
) and an endcharacter (>
), so it would look like this: <height:2342>
There will also be a lot of irrelevant data being written, thats why I decided to use the above form, so the python script can detect the relevant information and capture it.
My python script would check every char individually for the start-character <
, ideally as it is entered, and then capture the information until >
is received. I tried getting the input using inputchar = sys.stdin.read(1)
. But the problem here is that this reads from stdin
forever, until a newline (\n
) is captured, and then returns the first character entered.
I want this function to return the entered character as soon as it got send to stdin
, and not wait for a newline. How do I achive this?
Platform: Raspberry Pi Zero W, Raspbian Jessy, Python 2.7
I know I could use inputline = sys.stdin.readline()
and change the Arduino programm to send a newline after the information. Then analyze the whole line (which could be very long) and extract the information. But I don't feel this would be a clean way of doing this.
Update on Serial Port: Sadly I can't access the serial port directly from python because there is a second python script which has to write to the serial port. Since only one can access the port, the solution is to redirect the serial port to stdin
and stdout
. See my question Access one Serial Port with two Python Scripts