Better handling of KeyboardInterrupt in cmd.Cmd command line interpreter

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

    I wanted to do the same, so I searched for it and created basic script for understanding purposes, my code can be found on my GitHub

    So, In your code,

    instead of this

    if __name__ == '__main__':
        console = Console()
        console.cmdloop()
    

    Use this,

    if __name__ == '__main__':
        console = Console()
        try: 
           console.cmdloop()
        except KeyboardInterrupt:
           print ("print sth. ")
           raise SystemExit
    

    Hope this will help you out. well, it worked for me.

提交回复
热议问题