custom output when control-c is used to exit python script

空扰寡人 提交于 2021-01-28 11:18:44

问题


I would like the user to use control-c to close a script, but when control-c is pressed it shows the error and reason for close (which make sense). Is there a way to have my own custom output to the screen rather than what is shown? Not sure how to handle that specific error.


回答1:


You could use try..except to catch KeyboardInterrupt:

import time

def main():
    time.sleep(10)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('bye')



回答2:


use the signal module to define a handler for the SIGINT signal:

import signal
import sys

def sigint_handler(signal_number, stack_frame):
    print('caught SIGINT, exiting')
    sys.exit(-1)

signal.signal(signal.SIGINT, sigint_handler)
raw_input('waiting...')



回答3:


For general purpose code, handling the KeyboardInterrupt should suffice. For advanced code, such as threading, it is a whole different story. Here's a simple example.

http://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt

try:
    while 1:
        x = raw_input("Type something or press CTRL+C to end: ")
        print repr(x)
except KeyboardInterrupt:
    print "\nWe're done here."


来源:https://stackoverflow.com/questions/17533559/custom-output-when-control-c-is-used-to-exit-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!