Better handling of KeyboardInterrupt in cmd.Cmd command line interpreter

前端 未结 8 560
感情败类
感情败类 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

    Instead of using signal handling you could just catch the KeyboardInterrupt that cmd.Cmd.cmdloop() raises. You can certainly use signal handling but it isn't required.

    Run the call to cmdloop() in a while loop that restarts itself on an KeyboardInterrupt exception but terminates properly due to EOF.

    import cmd
    import sys
    
    class Console(cmd.Cmd):
        def do_EOF(self,line):
            return True
        def do_foo(self,line):
            print "In foo"
        def do_bar(self,line):
            print "In bar"
        def cmdloop_with_keyboard_interrupt(self):
            doQuit = False
            while doQuit != True:
                try:
                    self.cmdloop()
                    doQuit = True
                except KeyboardInterrupt:
                    sys.stdout.write('\n')
    
    console = Console()
    
    console.cmdloop_with_keyboard_interrupt()
    
    print 'Done!'
    

    Doing a CTRL-c just prints a new prompt on a new line.

    (Cmd) help
    
    Undocumented commands:
    ======================
    EOF  bar  foo  help
    
    (Cmd) <----- ctrl-c pressed
    (Cmd) <------ctrl-c pressed 
    (Cmd) ddasfjdfaslkdsafjkasdfjklsadfljk <---- ctrl-c pressed
    (Cmd) 
    (Cmd) bar
    In bar
    (Cmd) ^DDone!
    

提交回复
热议问题