1 回答
TA贡献1860条经验 获得超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
添加回答
举报