Skip to content

Instantly share code, notes, and snippets.

@justinmklam
Last active January 10, 2020 18:11
Show Gist options
  • Save justinmklam/5427548cd8436ca5c6ae53adb7d81a37 to your computer and use it in GitHub Desktop.
Save justinmklam/5427548cd8436ca5c6ae53adb7d81a37 to your computer and use it in GitHub Desktop.
Demonstrates simple usage of argparser.
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Describe the utility.'
)
# This is a required argument
parser.add_argument(
'filepath',
type=str,
help='Filepath to use.'
)
# This is used as a boolean flag. If set, the variable (with name 'all' as set by dest) is true
parser.add_argument(
'-A', '--all',
action='store_true', dest='all',
help='Use this flag to enable all.'
)
# Metavar is used in help as an example argument input. String will default to None if argument is not provided.
parser.add_argument(
'-i', '--individual',
metavar='"FIRSTNAME LASTNAME"', type=str, dest='individual',
help='First and last name. Single or double quotes must be used to capture the space.'
)
# If no dest is specified, it will use 'time'. Use default value if none is provided.
parser.add_argument(
'-t', '--time',
type=int,
help='Set time',
default=10
)
args = parser.parse_args()
print(f"all params: {args}")
print(f"all: {args.all}")
print(f"filepath: {args.filepath}")
print(f"individual: {args.individual}")
print(f"time: {args.time}")
# Input:
# python_argparser_example.py foobar
#
# Output:
# all params: Namespace(all=False, filepath='foobar', individual=None, time=10)
# all: False
# filepath: foobar
# individual: None
# time: 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment