1 回答

TA貢獻1860條經(jīng)驗 獲得超8個贊
您可以將線程與消息隊列一起使用:
from threading import Thread
from Queue import Queue
from datetime import datetime
import time
def chatbot(queue):
while True:
queue.put('CHATBOT: The time is now %s' % datetime.now())
time.sleep(5)
def user_input(queue):
while True:
queue.put('USER: ' + raw_input())
queue = Queue()
chatbot_thread = Thread(target=chatbot, args=(queue,))
input_thread = Thread(target=user_input, args=(queue,))
chatbot_thread.start()
input_thread.start()
while True:
print(queue.get())
示例輸入/輸出:
CHATBOT: The time is now 2019-03-01 07:42:43.975000
hello world
USER: hello world
CHATBOT: The time is now 2019-03-01 07:42:48.976000
CHATBOT: The time is now 2019-03-01 07:42:53.977000
foo bar
USER: foo bar
CHATBOT: The time is now 2019-03-01 07:42:58.977000
添加回答
舉報