猿问

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

我在教程中看到的所有程序都是控制台,代码从第一行到最后一行执行,如果有的话,一切都从第一行开始。由于某些事件,例如按键或代码中的某些事件,控制台程序是否有任何方法可以更改其执行方式?我想要做的最好的例子是路由器 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,您可以设置接口,同时路由器在后台进行路由。


塞尔吉奥 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()


慕少森
浏览 121回答 2
2回答

暮色呼如

从您的描述来看,您似乎正在寻找一种叫做多线程的东西:应用程序的一部分做一件事,另一部分做另一件事。

慕的地10843

whats_typed = input('Say Aah:')if whats_typed.strip() == 'Aah':    print('Thanks!')else:    print('Whoops. Your input was:', whats_typed)当程序运行时,上面会根据用户输入更改执行的内容。
随时随地看视频慕课网APP

相关分类

Python
我要回答