amphibient amphibient - 1 year ago 82
Python Question

Reading named command arguments

Can I use

to read named command line arguments that do not need to be in a specific order? I browsed through the documentation but most of it focused on displaying content based on the arguments provided (such as

Right now, my script reads ordered, unnamed arguments: foo-val bar-val


foo = sys.argv[1]
bar = sys.argv[2]

But I would like to change the input so that it is order agnostic by naming arguments: --bar=bar-val --foo=foo-val

Answer Source

You can use the Optional Arguments like so:

import argparse, sys


parser.add_argument('--bar', help='Do the bar option')
parser.add_argument('--foo', help='Foo the program')


print args
print sys

Then if you call it with ./prog --bar=bar-val --foo foo-val it prints:

Namespace(bar='bar-val', foo='foo-val')
['Untitled', '--bar=bar-val', '--foo', 'foo-val']

Or, if the user wants help argparse builds that too:

 $ ./prog -h
usage: Untitled [-h] [--bar BAR] [--foo FOO]

optional arguments:
  -h, --help  show this help message and exit
  --bar BAR   Do the bar option
  --foo FOO   Foo the program
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download