Reading named command arguments

You can use the Optional Arguments like so.

With this program:

#!/usr/bin/env python3

import argparse, sys

parser=argparse.ArgumentParser()

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

args=parser.parse_args()

print(f"Args: {args}\nCommand Line: {sys.argv}\nfoo: {args.foo}")
print(f"Dict format: {vars(args)}")

Make it executable:

$ chmod +x prog.py

Then if you call it with:

$ ./prog.py --bar=bar-val --foo foo-val

It prints:

Args: Namespace(bar="bar-val", foo='foo-val')
Command Line: ['./prog.py', '--bar=bar-val', '--foo', 'foo-val']
foo: foo-val
Dict format: {'bar': 'bar-val', 'foo': 'foo-val'}

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

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

options:
  -h, --help  show this help message and exit
  --bar BAR   Do the bar option
  --foo FOO   Foo the program

2022-08-30: Updated to Python3 this answer…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)