while True:
mess = raw_input('Type: ')
//other stuff
While user doesn't type anything, I can't do //other stuff
. How can I do, that other stuff would be executed, but, if user types anything at that time, mess would change its value?
while True:
mess = raw_input('Type: ')
//other stuff
While user doesn't type anything, I can't do //other stuff
. How can I do, that other stuff would be executed, but, if user types anything at that time, mess would change its value?
You should spawn your other stuff in a worker thread.
import threading
import time
import sys
mess = 'foo'
def other_stuff():
while True:
sys.stdout.write('mess == {}\n'.format(mess))
time.sleep(1)
t = threading.Thread(target=other_stuff)
t.daemon=True
t.start()
while True:
mess = raw_input('Type: ')
This is a trivial example with mess
as a global. Note that for thread-safe passing of objects between worker thread and main thread, you should use a Queue
object to pass things between threads, don't use a global.
As an alternative to using a worker thread you could poll whether the user input is available on Unix via select.select()
:
import select
import sys
def raw_input_timeout(prompt=None, timeout=None):
if prompt is not None:
sys.stdout.write(prompt)
sys.stdout.flush()
ready = select.select([sys.stdin], [],[], timeout)[0]
if ready:
# there is something to read
return sys.stdin.readline().rstrip('\n')
prompt = "First value: "
while True:
s = raw_input_timeout(prompt, timeout=0)
if s is not None:
mess = s # change value
print(repr(mess))
prompt = "Type: " # show another prompt
else:
prompt = None # hide prompt
# do other stuff
Each time the user presses Enter the mess
value is changed.