autocommand
autocommand is a Python library (current version 2.2.2) designed to simplify the creation of command-line programs from standard Python functions. It automatically converts a function's parameter signature into `argparse`-compatible command-line arguments and handles execution when the module is run as `__main__`. It has an active development status with a mature feature set.
Warnings
- breaking In autocommand 2.x, the behavior of calling an `@autocommand`-decorated function directly (i.e., outside of `if __name__ == '__main__'` without passing `__name__` or `True` to the decorator) changed. Instead of immediately executing the function, it now returns a callable wrapper function, typically `main(argv=None)`. If you were relying on direct execution for testing or embedding, you must update your calls.
- gotcha When an `autocommand`-decorated function is run as the main program, `autocommand` internally uses `sys.exit()` with the function's return value. This can bypass normal Python program flow and exception handling mechanisms, which might be unexpected in certain embedding or testing scenarios.
- gotcha Argument parsing errors (e.g., missing required arguments, invalid types) or the use of `-h`/`--help` will cause `SystemExit` to be raised by the underlying `argparse` mechanism. This is a standard behavior of `argparse` but can halt programs that don't explicitly handle it.
Install
-
pip install autocommand
Imports
- autocommand
from autocommand import autocommand
Quickstart
import os
from autocommand import autocommand
@autocommand(__name__)
def greet(name: str = 'World', excited: bool = False):
"""Greets the given name."""
message = f"Hello, {name}"
if excited:
message += '!'
print(message)
# To run from command line: python your_script.py John --excited
# To run as a function (e.g., in a test):
# if __name__ != '__main__':
# # In 2.x, calling greet() directly without __name__ returns a callable function
# # so this is how you'd explicitly call it if not running as __main__
# # For library usage, you might get the parser and call it like:
# # func = autocommand(False)(greet) # Pass False or omit argument to return wrapper
# # func(['Alice', '--excited'])