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()
.
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
kind="flag"
: boolean option; if the flag is included in the command then the argument will be set to Truekind="positional"
: required arguments that need not be prepended with a flagkind="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
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
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)
>>> 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!!!