Python输入和输出线程
我想创建一个python脚本,它从一个线程输出消息,同时仍然等待您在另一个线程上输入。这可能吗?如果是,怎么做 系统:Windows7 语言:Python 2.7 我试过从另一个问题修改这个:Python输入和输出线程,python,multithreading,Python,Multithreading,我想创建一个python脚本,它从一个线程输出消息,同时仍然等待您在另一个线程上输入。这可能吗?如果是,怎么做 系统:Windows7 语言:Python 2.7 我试过从另一个问题修改这个: import threading import time def message_loop(): while True: time.sleep(1) print "Hello World" thread = threading.Thread(target = m
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,您可以使用线程模块在不同的线程中启动它:
您现在应该开始获取输出。然后可以在主线程上运行输入位。您也可以在新线程中运行它,但在主线程中运行输入有一些优点。这是绝对可能的。如果您有一个打印输出的函数,我们称之为print_output,您可以使用线程模块在不同的线程中启动它: 您现在应该开始获取输出。然后可以在主线程上运行输入位。您也可以在新线程中运行它,但在主线程中运行输入有一些优点。这对我很有用。 代码在您输入“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')
这对我有用。
代码在您输入“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')
除了咖啡的问题,你读了什么?你看过Python文档了吗?我读过文档,也尝试过其他人编写的代码,但结果是,我需要按enter键,然后输出代码。这让Coffee的问题很难说,你读过什么?你看过Python文档了吗?我读过文档,也尝试过其他人编写的代码,但实际情况是,代码需要我按enter键,然后输出。它只告诉我如何执行线程,而不是我希望它执行的操作though@Pyro例如我无法重现你的问题。它对我来说很好,虽然我使用的是2.6而不是2.7,而且我也不使用Windows。这只是告诉我如何线程,它并没有达到我想要的效果though@Pyro例如我无法重现你的问题。它对我来说很好,尽管我使用的是2.6而不是2.7,而且我不使用Windows。