Skip to content

Instantly share code, notes, and snippets.

@alexcreek
Last active December 18, 2021 02:49
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 alexcreek/f83a153d72cecbc30f4592b5f4ad8810 to your computer and use it in GitHub Desktop.
Save alexcreek/f83a153d72cecbc30f4592b5f4ad8810 to your computer and use it in GitHub Desktop.
python argparse example
#!/usr/bin/env python3
# https://docs.python.org/3.9/library/argparse.html
import argparse
def parse_arguments():
parser = argparse.ArgumentParser(description='Argument Parser Template')
parser.add_argument('-b', '--basic', help='basic arg consuming option')
parser.add_argument('-v', '--verbose', help='increase output verbosity, flag', action='store_true')
parser.add_argument('-g', '--greedy', help='greedy narg=* arg', nargs='*')
parser.add_argument('-c', '--choices', help='choices demonstration', choices=['list', 'of', 'choices'])
parser.add_argument('-s', '--string', help='string coercion arg', type=str)
parser.add_argument('-i', '--integer', help='integer coercion arg', type=int)
parser.add_argument('-f', '--float', help='float coercion arg', type=float)
parser.add_argument('-r', '--required', help='required example arg', required=True)
return parser.parse_args()
def main(*args, **kwargs):
print(*args, **kwargs)
if __name__ == '__main__':
args = parse_arguments()
if args.verbose:
print('verbosity flag enabled')
if args.basic:
print(f'Basic arg is type: {type(args.basic)}')
if args.greedy:
print(args.greedy)
if args.choices:
print(f'Congratulations! You chose {args.choices}')
if args.string:
print(f'Your arg is a {type(args.string)}')
if args.integer:
print(f'Your arg is a {type(args.integer)}')
if args.float:
print(f'Your arg is a {type(args.float)}')
main(args.basic, args.greedy, args.choices)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment