Better handling of KeyboardInterrupt in cmd.Cmd command line interpreter

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

    In response to the following comment in this answer:

    This appears to be converging on a solution, but I don't know how to integrate it into my own code (above). I have to figure out the 'super' line. I need to try and get this working at some point in the future.

    super() would work in this answer if you have your class extend object in addition to cmd.Cmd. Like this:

    class Console(cmd.Cmd, object):
    
    0 讨论(0)
  • 2021-02-04 11:33

    Just add this inside the class Console(cmd.Cmd):

    
        def cmdloop(self):
            try:
                cmd.Cmd.cmdloop(self)
            except KeyboardInterrupt as e:
                self.cmdloop()
    

    Forget all the other stuff. This works. It doesn't make loops inside of loops. As it catches KeyboardInterrupt it calls do_EOF but only will execute the first line; since your first line in do_EOF is return do_exit this is fine.
    do_exit calls postloop.
    However, again, it only executes the first line after cmd.Cmd.postloop(self). In my program this is print "\n". Strangely, if you SPAM ctrl+C you will eventually see it print the 2nd line usually only printed on ACTUAL exit (ctrl+Z then enter, or typing in exit).

    0 讨论(0)
提交回复
热议问题