由于某些事件,例如,控制台程序是否有任何方法可以改变它们的执行方式按键或代码中的某些事件?

Is there any way for console programs to change their execution way, due to some event, like e.g. key press or some event in code?

我在教程中看到的所有程序都是控制台,代码从第一行执行到最后一行,如果有的话,一切都从第一行开始。由于某些事件,例如,控制台程序是否有任何方法可以改变它们的执行方式按键或代码中的某些事件?我想做的最好的例子是路由器 CLI。我在哪里可以找到这样的例子?

def main(): 
    while(True):
        initial_setup() #choose IPs to monitor
        while(True):
            do_some_work() # do monitor the IPs

我需要一些侦听器来检测按键,然后我进入初始设置,同时 do_some_work 工作并且只有在我完成 initial_setup do_some_work 中的附加更改后才能重新启动.

对不起,我是菜鸟,不太会解释,因为英语对我来说不是母语。我能说出的现实生活中最好的例子是路由器的 CLI,你可以设置接口,同时路由器在后台进行路由。

Sergio S 的代码:

import threading
import time

def hello():
    while(True):
        print("Hello")
        time.sleep(2)

def hi():
    while(True):
       print("hi")
       time.sleep(2)
def press_key():
    a=input()
    a=False
    return a
def circle():
    MrBoolean=True
    while(MrBoolean):
        thr=[]
        thr.append(threading.Thread(target=hello))
        thr.append(threading.Thread(target=hi))
        thr.append(threading.Thread(target=press_key))
        for i in thr:
            i.start()
        for i in thr:
            i.join()
        mrBoolean=thr[3] 
 def main():
    while(True):
        circle()

main()
whats_typed = input('Say Aah:')
if whats_typed.strip() == 'Aah':
    print('Thanks!')
else:
    print('Whoops. Your input was:', whats_typed)

当程序为 运行。

时,以上内容会根据用户输入更改执行的内容

根据您的描述,您似乎在寻找一种叫做多线程的东西:当应用程序的一部分做一件事时,另一部分做另一件事。有关详细信息,请参阅这些其他问题:How to use threading in Python? , How to stop a looping thread in Python?