Better handling of KeyboardInterrupt in cmd.Cmd command line interpreter

前端 未结 8 543
感情败类
感情败类 2021-02-04 11:00

While using python\'s cmd.Cmd to create a custom CLI, how do I tell the handler to abort the current line and give me a new prompt?

Here is a minimal example:

         


        
8条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 11:23

    You can catch the CTRL-C signal with a signal handler. If you add the code below, the interpreter refuses to quit on CTRL-C:

    import signal
    
    def handler(signum, frame):
        print 'Caught CTRL-C, press enter to continue'
    
    signal.signal(signal.SIGINT, handler)
    

    If you don't want to press ENTER after each CTRL-C, just let the handler do nothing, which will trap the signal without any effect:

    def handler(signum, frame):
        """ just do nothing """
    

提交回复
热议问题