[英]Python input and output threading
我想創建一個python腳本,從一個線程中打印出消息,同時仍在等待您輸入另一個線程。 這可能嗎? 如果是這樣,怎么辦?
系統:Windows 7
語言:Python 2.7
我已經試過了(從另一個問題修改):
import threading
import time
def message_loop():
while True:
time.sleep(1)
print "Hello World"
thread = threading.Thread(target = message_loop)
thread.start()
while True:
input = raw_input("Prompt> ")
但是發生的是:該程序等到我完成輸入后才輸出Hello World
。
絕對有可能。 如果您有一個打印輸出的函數(我們稱其為print_output
),則可以使用threading
模塊在另一個線程中啟動它:
>>> import threading
>>> my_thread = threading.Thread(target=print_output)
>>> my_thread.start()
現在,您應該開始獲取輸出。 然后,您可以在主線程上運行輸入位。 您也可以在新線程中運行它,但是在主線程中運行輸入有一些優點。
這對我有用。 在輸入“ q”之前,代碼將顯示消息
import threading
import time
def run_thread():
while True:
print('thread running')
time.sleep(2)
global stop_threads
if stop_threads:
break
stop_threads = False
t1 = threading.Thread(target=run_thread)
t1.start()
time.sleep(0.5)
q = ''
while q != 'q':
q = input()
stop_threads = True
t1.join()
print('finish')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.