Skip to content

Instantly share code, notes, and snippets.

@dunderrrrrr
Created February 21, 2020 13:44
Show Gist options
  • Save dunderrrrrr/9b761e00ff7e4c6f25f46358ce5b24c3 to your computer and use it in GitHub Desktop.
Save dunderrrrrr/9b761e00ff7e4c6f25f46358ce5b24c3 to your computer and use it in GitHub Desktop.
The argparse module makes it easy to write user-friendly command-line interfaces.

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

Basic template

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    # args goes here
    parser.add_argument('--check', action='store_true')

    args = parser.parse_args()
    if len(sys.argv)==1:
        parser.print_help(sys.stderr)
        sys.exit(1)

    if args.check:
        print("True")
    else:
        print("False")

Arguments

Having multiple args combined in one argument.

$ python script.py -a arg1 arg2

parser.add_argument('-a', action='store', nargs=2)

Settings true or false.

$ python script.py --check

parser.add_argument('--check', action='store_true')

Using defined options to force selection.

$ python script.py --check one
$ python script.py --check two

parser.add_argument('--check', choices=['one', 'two'])

Using args "no-args".

$ python script.py arg01 arg02

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    args = sys.argv[1:]
    print(args)

More can be found here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment