3
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?

good_evening
  • 21,085
  • 65
  • 193
  • 298
  • 1
    possible duplicate of [Reading input from raw_input() without having the prompt overwritten by other threads in Python](http://stackoverflow.com/questions/2082387/reading-input-from-raw-input-without-having-the-prompt-overwritten-by-other-th) – Greg Hewgill Feb 27 '12 at 02:10
  • I came across your article and decided to do some digging to help you out with your question. I don't know if you came across this article before but I found this article http://stackoverflow.com/questions/2082387/reading-input-from-raw-input-without-having-the-prompt-overwritten-by-other-th and the top-voted answer by user jhackworth seems to address the issue you are mentioning. I hope this helps or in the very least points you in the right direction! – Stephen Tetreault Feb 27 '12 at 02:03

2 Answers2

4

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.

wim
  • 338,267
  • 99
  • 616
  • 750
0

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670