Skip to content

Instantly share code, notes, and snippets.

@charlesreid1
Created July 23, 2019 22:28
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 charlesreid1/4f1f098380a07d1c4095d588bc21f500 to your computer and use it in GitHub Desktop.
Save charlesreid1/4f1f098380a07d1c4095d588bc21f500 to your computer and use it in GitHub Desktop.
A very simple argparse example. Takes one argument, a path to a folder (-d or --dir); prints whether that folder exists.
import os, sys
import argparse
"""
A Simple Argparse Program
That Works Just The Way
We Like It.
Charles Reid
July 2019
"""
def main(sysargs = sys.argv[1:]):
parser = get_argument_parser(sysargs)
# Make sure the user provided SOME arguments
if(len(sys.argv)==1):
parser.print_help(sys.stderr)
sys.exit(1)
# Parse the arguments
args = parser.parse_args(sysargs)
work_dir = args.dir
print("Working directory:")
print(work_dir)
print("Searching for directory on disk...")
if os.path.isdir(work_dir):
print("Found!")
else:
print("Does not exist!")
def get_argument_parser(sysargs):
"""Assemble and return an argument parser object"""
parser = argparse.ArgumentParser(prog = 'Test Program')
# https://stackoverflow.com/a/24181138
required_args = parser.add_argument_group('Required Arguments')
required_args.add_argument('-d', '--dir',
required=True,
help="""Specify the location on disk of the directory""")
return parser
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment