Plac: The Smartest Command Line Arguments Parser
Plac is a Python library (version 1.4.5) that simplifies command-line argument parsing by automatically generating parsers from function signatures. It works across various Python 3 versions and is known for its minimal dependencies, often relying only on the standard library. Releases are somewhat infrequent but target Python compatibility updates.
Warnings
- breaking The `plac` server functionality, which relied on Python's `asyncore` and `asynchat` modules, was removed in `plac` v1.4.0 due to their deprecation and subsequent removal in Python 3.12+. This affects users of `plac`'s experimental server, which is no longer directly supported by `plac` itself.
- gotcha Plac does not support the `destination` concept found in `argparse`. If an argument name in your function signature clashes with a Python keyword (e.g., trying to define `--yield`), it's impossible to implement directly. You must change the argument name or use `argparse` if such a name is critical.
- gotcha Plac does not directly support 'required options'. Its design philosophy aligns with `argparse`'s guideline that options should generally be optional. If a parameter is truly required, it should typically be defined as a positional argument in your function signature.
- gotcha `plac.call()` handles invalid command-line input by printing an error message to `stderr` and then raising a `SystemExit`. This behavior, while standard for CLI applications, can disrupt automated tests by abruptly exiting the Python interpreter.
- breaking Python 3.13.0a4 and newer versions have introduced changes in the help text output format. This can cause existing `plac` application tests to fail if they rely on exact string comparisons of the generated `help` output.
Install
-
pip install plac
Imports
- plac
import plac
- call
plac.call(main_function)
Quickstart
import plac
def main(model, iter: ('iterations for training', 'option', 'i', int)=100, debug: ('enable debug mode', 'flag', 'd')=False):
""" A script for machine learning """
print(f"Model: {model}, Iterations: {iter}, Debug: {debug}")
if __name__ == '__main__':
plac.call(main)