4

How to read users input when in loop (and without blocking work in this loop)?

I want to do some basic stuff, like switching DEBUG variable, print values of some variables etc on some specific keys that user will print, but my program work in constant loop, and this loop fire another threads. How can i do this?

SuitUp
  • 3,112
  • 5
  • 28
  • 41
  • what is this loop you refer to did you mean to include a code sample? – Dan D. Jan 26 '12 at 02:02
  • Code is few files big, so i think this is not possible, but it you ask what is inside, here it is: it has a lot of prints, it uses eventlet threads, use urllib and write and read from files. It is too complicated to paste it anywhere. – SuitUp Jan 26 '12 at 02:05
  • What OS are you running it on? – Keith Jan 26 '12 at 03:10
  • Windows currently, but i will run this script on linux too. – SuitUp Jan 26 '12 at 03:19

1 Answers1

5

Use threads:

import threading
import time

value = 3

def process():
    while True:
        print(value)
        time.sleep(1)

thread = threading.Thread(target=process)
thread.start()

while True:
    value = input('Enter value: ')

(Output gets kind of messed up here because of both loops printing stuff to the terminal but I think the idea should be clear.)

Rob Wouters
  • 15,797
  • 3
  • 42
  • 36
  • Be careful sharing variables between threads. You might want to use a mutex or pass data into a queue or deque – jdi Jan 26 '12 at 02:20
  • Definitely not the prettiest but hopefully it shows how to run something in a separate thread. – Rob Wouters Jan 26 '12 at 02:25
  • Oh I agree with your example completely. I was more just warning the OP to take that into consideration when he applies it. – jdi Jan 26 '12 at 02:42
  • I change only boolean variables and flush files, this shouldn't ruin anything, right? – SuitUp Jan 26 '12 at 03:21