Python : raw_input and print in a thread

落爺英雄遲暮 提交于 2019-12-23 23:05:43

问题


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 something like this:

-->whatiwWHATTHETHREADWRITErite

but I would like to get some thing like this

WHATTHETHREADWRITE
-->whatiwrite

Thank you!


回答1:


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

while 1:
    raw_input()     # Waiting for you to press Enter
    with lock:
        r = raw_input('--> ')
        # send your command to the thread

And then lock the background thread printing:

def worker(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



回答2:


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"



回答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.



来源:https://stackoverflow.com/questions/8861515/python-raw-input-and-print-in-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!