如何在主程序仍在运行时使用threading来实时获取用户输入的方法(Python)

2024-10-05 13:22:48 发布

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

在WHILE循环中,我想运行两个函数,一个是base函数,每次运行一次,另一个是user_input函数,当用户输入'disarm'时,程序可以运行user_input函数。 这两个函数需要在WHILE循环中才能一直运行。

如何编写函数来完成此任务?

因为它是实时的,所以我不能在线程中添加时间。

谢谢。

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时,它可以打印disarm并中断它。


Tags: 函数self程序inputbaseinitdefarm
1条回答
网友
1楼 · 发布于 2024-10-05 13:22:48

你真的需要更具体一点。为什么这些需要在线程中?你应该向我们展示你所做的努力,或者更详细地描述你正在努力实现的目标。

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

编辑:下面是一些清理后的代码,作为一个例子,以您的文章编辑和评论为基础。

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'

相关问题 更多 >

    热门问题