Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit the cmd loop of cmd module cleanly

Tags:

python

cmd

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.

like image 218
Simon Hughes Avatar asked Mar 21 '13 00:03

Simon Hughes


Video Answer


1 Answers

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
like image 84
isedev Avatar answered Nov 15 '22 21:11

isedev