当主线程仍在python中运行时,如何使用线程获取实时用户输入

编程入门 行业动态 更新时间:2024-10-27 18:17:58
本文介绍了当主线程仍在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中运行时,如何使用线程获取实时用户输入

本文发布于:2023-11-26 22:16:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635420.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   主线   如何使用   实时   用户

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!