Conditional command line arguments in Python using argparse

The argparse module offers a way to do this without implementing your own requiredness checks. The example below uses “subparsers” or “sub commands”. I’ve implemented a subparser for “dump” and one for “format”. import argparse parser = argparse.ArgumentParser() parser.add_argument(‘file’, help=’The file you want to act on.’) subparsers = parser.add_subparsers(dest=”subcommand”) subparsers.required = True # required since … Read more

Why use argparse rather than optparse?

As of python 2.7, optparse is deprecated, and will hopefully go away in the future. argparse is better for all the reasons listed on its original page (https://code.google.com/archive/p/argparse/): handling positional arguments supporting sub-commands allowing alternative option prefixes like + and / handling zero-or-more and one-or-more style arguments producing more informative usage messages providing a much … Read more

Specify date format for Python argparse input arguments

Per the documentation: The type keyword argument of add_argument() allows any necessary type-checking and type conversions to be performed … The argument to type can be any callable that accepts a single string. You could do something like: def valid_date(s): try: return datetime.strptime(s, “%Y-%m-%d”) except ValueError: msg = “not a valid date: {0!r}”.format(s) raise argparse.ArgumentTypeError(msg) … Read more

How to open file using argparse?

Take a look at the documentation: https://docs.python.org/3/library/argparse.html#type import argparse parser = argparse.ArgumentParser() parser.add_argument(‘file’, type=argparse.FileType(‘r’)) args = parser.parse_args() print(args.file.readlines())

Display help message with Python argparse when script is called without any arguments

This answer comes from Steven Bethard on Google groups. I’m reposting it here to make it easier for people without a Google account to access. You can override the default behavior of the error method: import argparse import sys class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write(‘error: %s\n’ % message) self.print_help() sys.exit(2) parser = MyParser() parser.add_argument(‘foo’, nargs=”+”) … Read more

argparse subparser monolithic help output

This is a bit tricky, as argparse does not expose a list of defined sub-parsers directly. But it can be done: import argparse # create the top-level parser parser = argparse.ArgumentParser(prog=’PROG’) parser.add_argument(‘–foo’, action=’store_true’, help=’foo help’) subparsers = parser.add_subparsers(help=’sub-command help’) # create the parser for the “a” command parser_a = subparsers.add_parser(‘a’, help=’a help’) parser_a.add_argument(‘bar’, type=int, help=’bar … Read more

How to parse multiple nested sub-commands using python argparse?

I came up with the same qustion, and it seems i have got a better answer. The solution is we shall not simply nest subparser with another subparser, but we can add subparser following with a parser following another subparser. Code tell you how: parent_parser = argparse.ArgumentParser(add_help=False) parent_parser.add_argument(‘–user’, ‘-u’, default=getpass.getuser(), help=’username’) parent_parser.add_argument(‘–debug’, default=False, required=False, action=’store_true’, … Read more