Last active
November 1, 2023 20:20
-
-
Save docPhil99/0bc03cc59f50b603b8ab37f3193794e8 to your computer and use it in GitHub Desktop.
Simple demo of argparse in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Simple demo of argparse in python, see http://zetcode.com/python/argparse/""" | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('name') # positional argument, note no dash! | |
parser.add_argument('-n', type=int, required=True, help="the number") # Required argument, must be a int, eg. -n 4 | |
parser.add_argument('-e', type=int, default=2, help="defines the value") # Optional argument with a default | |
parser.add_argument('-o', '--output', action='store_true', help="shows output") # a binary flag | |
parser.add_argument('chars', type=str, nargs=2, help='two strings') # requires two strings, stored in list of strings | |
"""For nargs: N an integer number of inputs, '?' one argument will be consumed if possible, if not use default. | |
'*' all arguments gathered into list, useful for multiple inputs for optional arguments. '+' is the same, but there must | |
be at least one input argument, eg demo.py -input a b c gives Namespace(input=['a','b','c'])""" | |
parser.add_argument('--now', dest='format', choices=['std', 'iso', 'unix', 'tz'], help="shows datetime in given format") | |
# restrict the parameters to a give list, also stores the data in args.format | |
# mutual exclusive options | |
group = parser.add_mutually_exclusive_group(required=False) | |
group.add_argument('-a', action='store_true') | |
group.add_argument('-b', action='store_true') | |
args = parser.parse_args() | |
print(f'The arguments are {args}') | |
# access each parameter | |
print(f'name: {args.name}') | |
# convert to a dictionary | |
args_dict = vars(args) | |
print(f'arg_dict: {args_dict}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment