Skip to content

Instantly share code, notes, and snippets.

@mnguyenngo
Last active September 20, 2018 22:47
Show Gist options
  • Save mnguyenngo/14df6fe17eb3ff76950c9a657a4109ee to your computer and use it in GitHub Desktop.
Save mnguyenngo/14df6fe17eb3ff76950c9a657a4109ee to your computer and use it in GitHub Desktop.
Implementing plac

plac Quickstart

plac makes parsing arguments from the command line easy.

plac Documentation: https://micheles.github.io/plac/


This short guide will only cover the decorator function plac.annotations().

Arguments

There are 6 arguments for plac.annotations().

  • help (str): Help message
  • kind (str): {"flag", "option", "positional"}
  • abbrev (str): abbreviation for argument name
  • type (str): convert the command line arguments from str to any Python type; by default there is no conversion and type=None
  • choices (list): valid choices for value of argument
  • metavar (str): name of the variable to be used in the usage message

Notes

  • kind="flag": boolean option; if the flag is included in the command then the argument will be set to True
  • kind="positional": required arguments that need not be prepended with a flag
  • kind="option": optional arguments and need to be prepended with a flag
  • Author of plac suggests to specify a one-character abbreviation for flags but not for options

Help Message

This is an example of the help message in the terminal.

>>> python implementing_plac.py -h

usage: implementing_plac.py [-h] [-t {Hello,Bye}] [-e] name

positional arguments:
  name                  User name

optional arguments:
  -h, --help            show this help message and exit
  -t {Hello,Bye}, --type {Hello,Bye}
                        Hello or Bye
  -e, --excited         With excitement

Example

import plac

@plac.annotations(
    # (help, kind, abbrev, type, choices, metavar)
    name=("User name", "positional"),
    type=("Hello or Bye", "option", "t", str, ["Hello", "Bye"]),
    excited=("With excitement", "flag", "e"))
def main(name, type, excited):
    if excited:
        end_with = "!!"
    else:
        end_with = ""
    if type == "Hello":
        print(f"Hello {name}!{end_with}")
    elif type == "Bye":
        print(f"Bye {name}!{end_with}")
    else:
        print(f"Yo {name}!{end_with}")


if __name__ == '__main__':
    plac.call(main)

Output

>>> python implementing_plac.py Nguyen
Yo Nguyen!

>>> python implementing_plac.py Nguyen -t Bye
Bye Nguyen!

>>> python implementing_plac.py Nguyen -t Hello -e
Hello Nguyen!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment