Skip to content Skip to sidebar Skip to footer

Python : Raw_input And Print In A Thread

I have a thread which can print some text on the console and the main program have a raw_input to control the thread. My problem is when I'm writing and the thread too I get someth

Solution 1:

You can create a lock, and perform all input and output while holding the lock:

import threading

stdout_lock = threading.Lock()

with stdout_lock:
    r = raw_input()

with stdout_lock:
    print"something"

Solution 2:

You have to syncronize your input with the thread output preventing them from happening at the same time.

You can modify the main loop like:

lock = threading.lock()

while1:
    raw_input()     # Waiting for you to press Enterwithlock:
        r = raw_input('--> ')
        # send your command to the thread

And then lock the background thread printing:

defworker(lock, ...):
    [...]
    with lock:
        print('what the thread write')

In short when you Press Enter you will stop the thread and enter in "input mode".

To be more specific, every time you Press Enter you will:

  • wait for the lock to be available
  • acquire the lock
  • print --> and wait for your command
  • insert your command
  • send that command to the thread
  • release the lock

So your thread will be stopped only if it tries to print when you are in "input mode", and in your terminal you'll get something like:

some previous output---> your input
THE THREAD OUTPUT

Solution 3:

Use something like curses to write the background task output to half the screen and your input/control stuff on the other half.

You can also fiddle with ANSI escape codes on most terminals.

Post a Comment for "Python : Raw_input And Print In A Thread"