python和编程新手。我有一个程序,包括几个类,模块和函数。程序从一个主类运行,该主类调用几个模块和函数
我的问题是如果用户想要在任何时候终止正在运行的程序,如何实现keyboardinterrupt。我是否需要在所有功能中实现'try / except'方法?或者这可以在主函数中实现?
要在任何时刻捕获中断,我是否需要在所有调用函数中使用try / except?
def KEYBOARD_INTERRUPT():
while True:
yesnoinput=raw_input('Do you want to exit from software [Y/N]:')
if yesnoinput=='y' or yesnoinput.upper()=='Y':
sys.exit()
elif yesnoinput=='n' or yesnoinput.upper()=='N':
break
else:
continue
def A():
while True:
try:
userInput=raw_input("Please enter A")
if userInput=='A':
break
else:
continue
except KeyboardInterrupt:
KEYBOARD_INTERRUPT()
def B():
userInput=raw_input("Please enter B")
if userInput=='B':
break
else:
continue
def main():
try:
A()
B()
except:
KEYBOARD_INTERRUPT()
当主程序调用函数B时,此时如果用户按下keyboardInterrupt,程序将退出并出现错误,我担心如果我想处理像KEYBOARD_INTERRUPT这样的函数我需要在函数等功能中实现这个功能?A
我明白了吗?
答案 0 :(得分:0)
您可以执行以下操作:
try:
...
except KeyboardInterrupt:
Do something
答案 1 :(得分:0)
异常向上流动,在每个函数执行块结束时终止。如果你想要的只是一个好消息,请在主要的顶部抓住它。这个脚本有两个主电源 - 一个捕获,一个不捕获。正如您所看到的,非捕获器显示了每个函数执行中的堆栈跟踪,但它有点难看。捕手掩盖了所有这些 - 尽管它仍然可以将信息写入日志文件中。
import sys
import time
def do_all_the_things():
thing1()
def thing1():
thing2()
def thing2():
time.sleep(120)
def main_without_handler():
do_all_the_things()
def main_with_handler():
try:
do_all_the_things()
except KeyboardInterrupt:
sys.stderr.write("Program terminated by user\n")
exit(2)
if __name__ == "__main__":
# any param means catch the exception
if len(sys.argv) == 1:
main_without_handler()
else:
main_with_handler()
从控制台运行它并点击ctrl-c然后你得到:
td@mintyfresh ~/tmp $ python3 test.py
^CTraceback (most recent call last):
File "test.py", line 26, in <module>
main_without_handler()
File "test.py", line 14, in main_without_handler
do_all_the_things()
File "test.py", line 5, in do_all_the_things
thing1()
File "test.py", line 8, in thing1
thing2()
File "test.py", line 11, in thing2
time.sleep(120)
KeyboardInterrupt
td@mintyfresh ~/tmp $
td@mintyfresh ~/tmp $
td@mintyfresh ~/tmp $ python3 test.py handled
^CProgram terminated by user