[英]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.