Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Last active February 4, 2022 07:58
Show Gist options
  • Save gustavorv86/cd47fc591374837b2439a528dc94b2a9 to your computer and use it in GitHub Desktop.
Save gustavorv86/cd47fc591374837b2439a528dc94b2a9 to your computer and use it in GitHub Desktop.
Python Argparse example
#!/usr/bin/env python3
import argparse
import sys
if __name__ == "__main__":
"""
Running examples:
$ ./argparse_example.py
usage: argparse_example.py [-h] --strparam STRPARAM [--boolparam]
[--intparam INTPARAM] [--append APPEND_LIST]
argparse_example.py: error: the following arguments are required: --strparam/-s
$ ./argparse_example.py -h
usage: argparse_example.py [-h] --strparam STRPARAM [--boolparam]
[--intparam INTPARAM] [--append APPEND_LIST]
Application description
optional arguments:
-h, --help show this help message and exit
--strparam STRPARAM, -s STRPARAM
String parameter mandatory
--boolparam, -b Boolean flag parameter
--intparam INTPARAM, -i INTPARAM
Int parameter
--append APPEND_LIST, -a APPEND_LIST
Add values to a list
$ ./argparse_example.py -s "hello world"
Namespace(append_list=[], boolparam=False, intparam=0, strparam='hello world')
$ ./argparse_example.py -s "hello world" -b
Namespace(append_list=[], boolparam=True, intparam=0, strparam='hello world')
$ ./argparse_example.py -s "hello world" -b -i 9
Namespace(append_list=[], boolparam=True, intparam=9, strparam='hello world')
$ ./argparse_example.py -s "hello world" -b -i 9 -a foo -a bar
Namespace(append_list=['foo', 'bar'], boolparam=True, intparam=9, strparam='hello world')
"""
parser = argparse.ArgumentParser(description="Application description")
parser.add_argument("--strparam", "-s", dest="strparam", type=str, action="store", default=None, required=True, help="String parameter mandatory")
parser.add_argument("--boolparam", "-b", dest="boolparam", action="store_true", default=False, help="Boolean flag parameter")
parser.add_argument("--intparam", "-i", dest="intparam", type=int, action="store", default=0, help="Int parameter")
parser.add_argument("--append", "-a", dest="append_list", action='append', default=[], help="Add values to a list")
args = parser.parse_args(sys.argv[1:])
print(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment