python多线程在屏幕上的输入输出处理

2024-07-04 06:41:56 发布

您现在位置: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>")

“>;”只是一个接收符号,但当我从另一个线程打印消息时,我希望在下一行打印“>;”。
预期产出:

^{pr2}$

我展示的代码不起作用,任何帮助都很感激。在


Tags: namefromimportgtiftimemaindef
1条回答
网友
1楼 · 发布于 2024-07-04 06:41:56

, I only want to find a way to print message from other thread and then cursor and ">" on the next line of the message

你需要两个线程,而不仅仅是一个线程,来说明你正在努力工作的想法。在

让我们来看看这个简单的例子。我们必须创建两个线程,在这种情况下,我们需要使用[Queue][1]在线程之间传递数据。This answer可以帮助解释为什么在线程环境中应该首选队列。在

在我们的示例中,您将更新第一个线程中的队列(放入队列中),并打印保存在另一个线程中的消息(从队列中获取)。如果队列为空,则不必打印任何值。在

这个例子可以作为一个很好的起点。在

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

这个例子应该是一个起点,如果你有任何其他问题,让我们知道。在

相关问题 更多 >

    热门问题