简体   繁体   English

Python输入和输出线程

[英]Python input and output threading

I want to create a python script that prints out messages from one thread, while still waiting for you to input on another. 我想创建一个python脚本,从一个线程中打印出消息,同时仍在等待您输入另一个线程。 Is this possible? 这可能吗? And if so, how? 如果是这样,怎么办?

System: Windows 7 系统:Windows 7

Language: Python 2.7 语言:Python 2.7

I have tried this (modified from a different question): 我已经试过了(从另一个问题修改):

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> ")

But what happens is: the program waits until I have finished inputting before it outputs Hello World . 但是发生的是:该程序等到我完成输入后才输出Hello World

It's absolutely possible. 绝对有可能。 If you have a function that prints output (let's call it print_output ) you can start it up in a different thread using the threading module: 如果您有一个打印输出的函数(我们称其为print_output ),则可以使用threading模块在另一个线程中启动它:

>>> import threading
>>> my_thread = threading.Thread(target=print_output)
>>> my_thread.start()

You should now start getting your output. 现在,您应该开始获取输出。 You can then run the input bit on the main thread. 然后,您可以在主线程上运行输入位。 You could also run it in a new thread, but there are some advantages to running input in the main thread. 您也可以在新线程中运行它,但是在主线程中运行输入有一些优点。

This works for me. 这对我有用。 The code prints message before you input 'q' 在输入“ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM