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

Accepting a dictionary as an argument with argparse and python [duplicate]

I do not think it is possible to pass a dictionary as an argument in the command line because there doesn’t exist a conversion function from string to dict (EDIT: A hack is possible which gives similar behaviour, see below). What you are essentially telling python to do is: dict(“{‘key1’: ‘value1’}”) Which if you try … 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())

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

Argparse – do not catch positional arguments with `nargs`.

There is a bug report on this: http://bugs.python.org/issue9338 argparse optionals with nargs=”?”, ‘*’ or ‘+’ can’t be followed by positionals A simple (user) fix is to use — to separate postionals from optionals: ./test.py -o 0.21 0.11 0.33 0.13 — 100 I wrote a patch that reserves some of the arguments for use by the … Read more

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

Call function based on argparse

Since it seems like you want to run one, and only one, function depending on the arguments given, I would suggest you use a mandatory positional argument ./prog command, instead of optional arguments (./prog –command1 or ./prog –command2). so, something like this should do it: FUNCTION_MAP = {‘top20’ : my_top20_func, ‘listapps’ : my_listapps_func } parser.add_argument(‘command’, … 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

tech