控制台程序是否有办法由于某些事件(例如按键或代码中的某些事件)而更改其执行方式?



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

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

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

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

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

从你的描述来看,你似乎在寻找一种叫做多线程的东西:虽然应用程序的一部分做一件事,另一部分做另一件事。有关更多详细信息,请参阅以下其他问题:如何在 Python 中使用线程?,如何在 Python 中停止循环线程?

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

上述内容根据程序运行时的用户输入更改执行的内容。

最新更新