How to easily exit the cmd loop of the cmd module

I am using the cmd module in Python to create a small interactive command line. However, from this documentation: http://docs.python.org/2/library/cmd.html , it is not clear that this is a clean way to exit a program (i.e. Cmdloop) programmatically.

Ideally, I want to issue some exit command on the command line, and it will exit the program.

+6
source share
1 answer

You need to override the postcmd method:

Cmd.postcmd (stop, line)

The hook method executed immediately after sending the command. This method is a stub in Cmd; it exists to be overridden by subclasses. line is the command line that was executed, and stop is a flag that indicates whether execution will stop after calling postcmd (); this will be the return value of the onecmd () method. the return value of this method will be used as the new value for the internal flag that corresponds to the stop; returning false will result in an interpretation to continue.

And from the cmdloop documentation:

This method will return when the postcmd () method returns true value. The stop argument to postcmd () is the return value from the command matching do _ * ().

In other words:

 import cmd class Test(cmd.Cmd): # your stuff (do_XXX methods should return nothing or False) def do_exit(self,*args): return True 
+11
source

All Articles