[英]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>")
“>”只是一個接收符號,但是當我從另一個線程打印一條消息時,我想在下一行打印“>”。
預期產量:
haha
> cursor should be in this line and continue to receive the input
我展示的代碼不起作用,任何幫助表示贊賞。
,我只想找到一種方法從其他線程打印消息,然后在消息的下一行打印光標和“>”
你需要兩個線程,而不僅僅是一個,來說明你正在努力的想法。
讓我們考慮一下這個簡單的例子。 我們必須創建兩個線程,在這種情況下我們需要使用[Queue][1]
在線程之間傳遞數據。 這個答案可以幫助解釋為什么在線程環境中首選隊列。
在我們的示例中,您將更新第一個線程中的隊列(放入隊列中),並打印您在另一個線程中保存的消息(從隊列中獲取)。 如果隊列為空,我們不必打印任何值。
這個例子可以是一個很好的起點。
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()
這個例子應該是一個起點,如果您有任何其他問題,請告訴我們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.