Amperand
Amperand

Reputation: 3

How to keep a While True loop running with raw_input() if inputs are seldom?

I'm currently working on a project where I need to send data via Serial persistently but need to occasionally change that data based in new inputs. My issue is that my current loop only functions exactly when a new input is offered by raw_input(). Nothing runs again until another raw_input() is received.

My current (very slimmed down) loop looks like this:

while True:
    foo = raw_input()
    print(foo)

I would like for the latest values to be printed (or passed to another function) constantly regardless of how often changes occur.

Any help is appreciated.

Upvotes: 0

Views: 371

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155684

The select (or in Python 3.4+, selectors) module can allow you to solve this without threading, while still performing periodic updates.

Basically, you just write the normal loop but use select to determine if new input is available, and if so, grab it:

import select

while True:
    # Polls for availability of data on stdin without blocking
    if select.select((sys.stdin,), (), (), 0)[0]:
        foo = raw_input()
    print(foo)

As written, this would print far more than you probably want; you could either time.sleep after each print, or change the timeout argument to select.select to something other than 0; if you make it 1 for instance, then you'll update immediately when new data is available, otherwise, you'll wait a second before giving up and printing the old data again.

Upvotes: 1

Cosinux
Cosinux

Reputation: 321

How will you type in your data at the same time while data is being printed?

However, you can use multithreading if you make sure your source of data doesn't interfere with your output of data.

import thread

def give_output():
    while True:
        pass  # output stuff here

def get_input():
    while True:
        pass  # get input here

thread.start_new_thread(give_output, ())
thread.start_new_thread(get_input, ())

Your source of data could be another program. You could connect them using a file or a socket.

Upvotes: 0

Related Questions