Search code examples
python-2.7cmdargparse

Manually pass commands into argparse? | Python 2.7


I am making a terminal game using Python's wonderful Cmd library. But i was curious if i could somehow put argparse code into it. Like use argparse to handle the 'args' from my cmd.Cmd() class. To do this, i was really hoping that argparse had a way to manually pass args into it. I skimmed over the docs, but didn't notice anything like that.


Solution

  • parse_args() takes an optional argument args with a list (or tuple) of to parse. parse_args() (without arguments) is equivalent to parse_args(sys.argv[1:]):

    In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv.

    If you do not have a tuple, but a single string, shell-like argument splitting can be accomplished using shlex.split()

    >>> shlex.split('"A" B C\\ D')
    ['A', 'B', 'C D']   
    

    Note that argparse will print usage and help messages as well as exit() on fatal errors. You can override .error() to handle errors yourself:

    class ArgumentParserNoExit(argparse.ArgumentParser):
        def error(self, message):
            raise ValueError(message) # or whatever you like