Python输入和输出线程

2024-04-20 08:41:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个python脚本,它打印出一个线程的消息,同时仍在等待您在另一个线程上输入消息。这可能吗?如果是,怎么办?在

系统:Windows 7

语言:Python2.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。在


Tags: import脚本looptrue消息messagehelloworld
2条回答

这是绝对可能的。如果您有一个打印输出的函数(我们称之为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')

相关问题 更多 >