简体   繁体   English

如何使用多线程为python处理屏幕上的输入和输出

[英]How to handle the input and output on screen with multithread for python

from threading import *
import time
def handleInput():
    time.sleep(2)
    print "\rhaha\n>",
if __name__ == "__main__":
    worker = Thread(target=handleInput)
    worker.daemon = True
    worker.start()
    clientInput = raw_input("\r>")

">" is just a receiving sign, but when I print a message from another thread, I want to print the ">" on the next line. “>”只是一个接收符号,但是当我从另一个线程打印一条消息时,我想在下一行打印“>”。
The expected output: 预期产量:

haha
> cursor should be in this line and continue to receive the input

The code I show is not working, any help appreciated. 我展示的代码不起作用,任何帮助表示赞赏。

, I only want to find a way to print message from other thread and then cursor and ">" on the next line of the message ,我只想找到一种方法从其他线程打印消息,然后在消息的下一行打印光标和“>”

You need two threads, not just one, to illustrate the idea that you are trying to work on. 你需要两个线程,而不仅仅是一个,来说明你正在努力的想法。

Let's consider this quick example. 让我们考虑一下这个简单的例子。 We have to create two threads, in this case we need to use a [Queue][1] to pass data between threads. 我们必须创建两个线程,在这种情况下我们需要使用[Queue][1]在线程之间传递数据。 This answer can help explain why Queues should be preferred in a threaded environment. 这个答案可以帮助解释为什么在线程环境中首选队列。

In our example, you are going to update the queue in the first thread (put in the queue), and printing the message that you saved in the other thread (get it from the queue). 在我们的示例中,您将更新第一个线程中的队列(放入队列中),并打印您在另一个线程中保存的消息(从队列中获取)。 If the queue is empty, we don't have to print any value. 如果队列为空,我们不必打印任何值。

This example can be a good starting point. 这个例子可以是一个很好的起点。

from threading import *
import time
import Queue # Queue in python2.x


def updateInput(messages):
    text= "haha" #"This is just a test"
    messages.put(text)
    #anothertext= "haha" #"This is just a test"
    #messages.put(anothertext)


def handleInput(messages):
    try:
        while True: # Optional, you can loop to, continuously, print the data in the queue
            if not messages.empty():
                text= messages.get()
                print text

            clientInput = raw_input("\r>")
    except KeyboardInterrupt:
        print "Done reading! Interrupted!"

if __name__ == "__main__":
    messages = Queue.Queue()
    writer = Thread(target=updateInput, args=(messages,))
    worker = Thread(target=handleInput, args=(messages,))

    writer.start()
    worker.start()

    writer.join()
    worker.join()

This example should be a starting point, if you have any other question, let us know. 这个例子应该是一个起点,如果您有任何其他问题,请告诉我们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM