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?

4
  • what is this loop you refer to did you mean to include a code sample? Commented Jan 26, 2012 at 2: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. Commented Jan 26, 2012 at 2:05
  • What OS are you running it on? Commented Jan 26, 2012 at 3:10
  • Windows currently, but i will run this script on linux too. Commented Jan 26, 2012 at 3:19

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

4 Comments

Be careful sharing variables between threads. You might want to use a mutex or pass data into a queue or deque
Definitely not the prettiest but hopefully it shows how to run something in a separate thread.
Oh I agree with your example completely. I was more just warning the OP to take that into consideration when he applies it.
I change only boolean variables and flush files, this shouldn't ruin anything, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.