Skip to content

Instantly share code, notes, and snippets.

@FanchenBao
Created August 15, 2022 18:59
Show Gist options
  • Save FanchenBao/b582a1affbbbeca5acbeb67ca8fe06af to your computer and use it in GitHub Desktop.
Save FanchenBao/b582a1affbbbeca5acbeb67ca8fe06af to your computer and use it in GitHub Desktop.
Template for creating a Python script that accepts command line arguments
from argparse import ArgumentParser, RawDescriptionHelpFormatter
ef get_argument_parser() -> ArgumentParser:
"""Acquire command line arguments
:return: The argument parser
:rtype: ArgumentParser
"""
parser = ArgumentParser(
description='''
Description of the general purpose of this script.
Highlight any key features or gotchas if necessary.
Usage:
python3 foo.py \
--single_arg hello \
--list_args 123, 456 \
--some_flag \
''',
formatter_class=RawDescriptionHelpFormatter,
)
parser.add_argument(
'-s', '--single_arg',
dest='single_arg',
type=str,
required=True,
help='REQUIRED. Description of the purpose of single_arg',
)
parser.add_argument(
'-l', '--list_args',
dest='list_args',
required=False,
type=int,
default=[],
nargs='+',
help='Optinal. Description of the purpose of list_args',
)
parser.add_argument(
'-f', '--some_flag',
dest='some_flag',
required=False,
default=False,
action='store_true',
help='Optional. A flag, if set, does something',
)
return parser
def main():
parser: ArgumentParser = get_argument_parser()
args = parser.parse_args()
# use args as such
args.single_arg
args.list_args
args.some_flag
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment