Skip to content

Instantly share code, notes, and snippets.

@RobVaughn
Last active October 28, 2023 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobVaughn/1f39deb0fe20db3eaa93ade4074a1258 to your computer and use it in GitHub Desktop.
Save RobVaughn/1f39deb0fe20db3eaa93ade4074a1258 to your computer and use it in GitHub Desktop.
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