The smartest command line arguments parser in the world
Maintained. Last release 3 months ago, commits in 4 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install placPlac: parsing the command line the easy way
plac is a Python package that can generate command line parameters
from function signatures.
plac works on Python 2.6 through all versions of Python 3.
plac has no dependencies beyond modules already present in the Python
standard library.
plac implements most of its functionality in a single file that may be
included in your source code.
Quickstart
plac can automatically generate command line parameters from a function signature.
import plac
def main(model, iter=100, debug=False):
"""
A script for machine learning
"""
print (model, iter, debug)
if __name__ == '__main__':
# Execute function via plac.call()
plac.call(main)
The program above can now take parameters from the command line like so:
python example.py A 1000
Running the script with no parameters as python example.py would print:
usage: example.py [-h] model [iter] [debug]
example.py: error: the following arguments are required: model
In addition, the program can also generate a help message:
python example.py -h
Produces the following output:
usage: example.py [-h] model [iter] [debug]
A script for machine learning
positional arguments:
model
iter [100]
debug [False]
options:
-h, --help show this help message and exit
Additional customization
When you need more control plac offers three decorators to describe positional, option and flag type parameters:
import plac
# Add decorators to the function
@plac.pos('model', help="model name", choices=['A', 'B', 'C'])
@plac.opt('iter', help="iterations", type=int)
@plac.flg('debug', help="debug mode")
def main(model, iter=100, debug=False):
"""
A script for machine learning
"""
print (model, iter, debug)
if __name__ == '__main__':
# Execute function via plac.call().
plac.call(main)
That will produce the following help:
usage: example.py [-h] [-i 100] [-d] {A,B,C}
A script for machine learning
positional arguments:
{A,B,C} model name
options:
-h, --help show this help message and exit
-i 100, --iter 100 iterations
-d, --debug debug mode
Decorator reference
To use plac all you need to know are the following three decorators: