Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python 'argparse' Cookbook
### argparse Examples
Snippet for short and long version flags:
parser.add_argument('-b', '--block',
nargs="?",
action='store',
dest='block',
metavar='block',
help='stores a value in block for -b or --block')
Snippet for on/off flags like verbose, silent, etc:
parser.add_argument('-q', '--silent',
action='store_true',
default=False,
help='supress all output')
Snippet for flag without arguments:
parser.add_argument('-f', '--flag',
action='store_true',
help='[flag is set or not]')
Snippet for: program.py [flag [argument]]
parser.add_argument('flag',
nargs=argparse.REMAINDER,
metavar='[flag [argument]]',
help='flag with optional argument')
args = parser.parse_args()
[...]
if len(args.flag) > 1:
argument = args.flag[1]
Snippet for flag with a single optional argument, set to default value if omitted:
parser.add_argument('-s', '--show',
nargs='?',
const=DEFAULT,
action='store',
metavar='argument',
dest='show',
type=str,
help='show has default or argument to flag')
mkaz.blog: https://mkaz.blog/code/python-argparse-cookbook/
Ariel Balter: https://gist.github.com/abalter/605773b34a68bb370bf84007ee55a130
Martin Thoma: https://martin-thoma.com/how-to-parse-command-line-arguments-in-python/
### Tools
Click: http://click.pocoo.org/
Docopt: https://github.com/docopt/docopt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.