티스토리 뷰
다음과 같이 할 수 있습니다.
try:
...
except KeyboardInterrupt:
Do something
-------------------예외가 스택 위로 흘러 가면서 각 함수 실행 블록이 종료됩니다. 당신이 원하는 것이 좋은 메시지라면, 당신의 메인에서 그것을 잡으십시오. 이 스크립트에는 두 개의 전원이 있습니다. 하나는 잡는 것이고 다른 하나는 그렇지 않은 것입니다. 보시다시피 non-catcher는 각 함수가 실행을 중단했지만 다소 추한 스택 추적을 보여줍니다. 캐처는 원하는 경우 로그 파일에 정보를 기록 할 수 있지만 모든 것을 마스킹합니다.
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
출처
https://stackoverflow.com/questions/39970040
댓글