Search code examples
pythoncmd

How to exit the cmd loop of cmd module cleanly


I'm using the cmd module in Python to build a little interactive command-line program. However, from this documentation: http://docs.python.org/2/library/cmd.html, it is not clear that what is a clean way to exit the program (i.e. the cmdloop) programmatically.

Ideally, I want to issue some command exit on the prompt, and that will exit the program.


Solution

  • You need to override the postcmd method:

    Cmd.postcmd(stop, line)

    Hook method executed just after a command dispatch is finished. This method is a stub in Cmd; it exists to be overridden by subclasses. line is the command line which was executed, and stop is a flag which indicates whether execution will be terminated after the call to 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 which corresponds to stop; returning false will cause interpretation to continue.

    And from the cmdloop documentation:

    This method will return when the postcmd() method returns a true value. The stop argument to postcmd() is the return value from the command’s corresponding do_*() method.

    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