在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中运行时,如何使用线程获取实时用户输入
发布评论