Better handling of KeyboardInterrupt in cmd.Cmd command line interpreter

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

    I'm currently working on a creation of a Shell by using the Cmd module. I've been confronted with the same issue, and I found a solution.

    Here is the code:

    class Shell(Cmd, object)
    ...
        def cmdloop(self, intro=None):
            print(self.intro)
            while True:
                try:
                    super(Shell, self).cmdloop(intro="")
                    break
                except KeyboardInterrupt:
                    print("^C")
    ...
    

    Now you have a proper KeyboardInterrupt (aka CTRL-C) handler within the shell.

提交回复
热议问题