当主线程仍在python中运行时,如何使用线程获取实时用户输入 [英] How to use threading to get user input realtime while main still running in python

查看:397
本文介绍了当主线程仍在python中运行时,如何使用线程获取实时用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WHILE循环中,我想运行两个函数,一个是基本函数,它将每次运行,另一个是user_input函数,当用户输入撤防"时,程序可以运行user_input函数. WHILE循环中需要这两个功能,因此可以一直运行.

In the WHILE loop, I wanna run two function, one is base function, which will run everytime, the other is user_input function, when user input 'disarm', program can run user_input function. This two function need in WHILE loop so can run all the time.

我该怎么写函数来完成此任务?

How could I do to write a function to accomplish this?

因为它是实时的,所以我无法在线程中添加时间.睡眠.

Because its realtime so I cant add time.sleep in threading.

谢谢.

import threading

class BackInput(threading.Thread):
    def __init__(self):
        super(BackInput, self).__init__()


    def run(self):
        self.input = raw_input()

while True:
    threading1 = BackInput()
    threading1.start()
    threading1.join()
    if threading1.input == 'disarm':
        print 'Disarm'
        break
    print 'Arm'

在这段代码中,程序应该每秒打印一次Arm,当我键入撤防时,它可以打印Disarm并将其破坏.

In this code, the program should print Arm every second, when I typed disarm, it can print Disarm and break it.

推荐答案

您确实需要更加具体.为什么这些需要在线程中?您应该向我们展示您尝试过的事情,或者更详细地描述您想要完成的事情.

You really need to be more specific. Why do these need to be in threads? You should show us what you have tried, or describe in more detail what you are trying to accomplish.

在当前设置中,您正在将线程放入循环中,因此它不能独立于每个用户输入而运行.

In your current setup, you are putting the thread inside a loop, so it can't run independently of each user input.

已以下是一些清理后的代码,以您的帖子编辑和评论为基础,为您提供示例.

edited: here is some cleaned up code as an example for you, based on your post edits and comments.

import threading
import time
import sys

def background():
        while True:
            time.sleep(3)
            print 'disarm me by typing disarm'


def other_function():
    print 'You disarmed me! Dying now.'

# now threading1 runs regardless of user input
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()

while True:
    if raw_input() == 'disarm':
        other_function()
        sys.exit()
    else:
        print 'not disarmed'

这篇关于当主线程仍在python中运行时,如何使用线程获取实时用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆