Search code examples
pythonpython-2.7arduinostdinarduino-yun

Python 2.7: read from stdin without prompting


I'm trying to make an Arduino Yun alarm system. It needs to make requests to my web server to update its stats. It also needs to monitor a button and a motion sensor. The Linux side is running a python script that will make web requests. I need to have the Arduino send its status to the python script. In the python script, I need to read from the Arduino side. I can do that with print raw_input(), but I want it to only read if there is something available, I don't want it to block if nothing is available. For example:

import time
while 1:
    print "test"
    time.sleep(3)
    print raw_input()
    time.sleep(3)

If I run it, I want it to print:

test

(6 seconds later)

test

Instead of

test
(Infinite wait until I type something in)

I've tried threads, but they're a little hard to use.


Solution

  • I looked at jakekimds's comment, and I saw that I could just do:

    while 1:
        rlist,_,_=select([sys.stdin],[],[],0)
        content=""
        while rlist:
            content+=raw_input()
            rlist,_,_=select([sys.stdin],[],[],0)
        print "blocking task - content:"+content
        time.sleep(5)
    

    This will:

    1. If content from stdin is available, then store it in content.
    2. Execute a blocking task.
    3. Sleep for 5 seconds.
    4. Go back to step 1.