cli-exit-tools
cli-exit-tools (v1.2.7) is an actively maintained Python library designed to facilitate the proper and controlled exiting of command-line interface (CLI) applications. It provides functionalities to print formatted exception messages, optionally include traceback information, retrieve appropriate exit codes from exceptions, and ensure output streams are flushed correctly before termination. The library targets Python 3.8 and newer, with a focus on robust error handling for CLI tools.
Warnings
- gotcha Default traceback behavior might be unexpected. The `print_exception_message` function's `trace_back` parameter defaults to a value (often from an internal `config` object) that can be influenced by CLI options. Developers should explicitly set `trace_back=True` if they consistently want full tracebacks, or ensure their CLI configuration correctly controls this behavior, otherwise, tracebacks might be suppressed by default.
- gotcha Incorrect import path for core utilities. Users commonly attempt to import functions like `print_exception_message` directly from the top-level `cli_exit_tools` package. However, these utilities are located within the `cli_exit_tools` module itself, requiring `from cli_exit_tools import cli_exit_tools` to access them.
- breaking Changes to exit code semantics or output structure can break consuming scripts. As with any CLI utility, future versions changing the default exit codes returned by `get_exit_code_from_exception` or modifying the format of messages printed by `print_exception_message` (e.g., switching from plain text to JSON, or reordering output) could break automated scripts or parsers relying on consistent output.
Install
-
pip install cli-exit-tools
Imports
- cli_exit_tools
from cli_exit_tools import cli_exit_tools
Quickstart
import sys
from cli_exit_tools import cli_exit_tools
def run_cli_task():
"""Simulates a task in a CLI application that might raise an error."""
try:
# Simulate an operation that causes an error, e.g., division by zero
# Or an invalid type conversion
value = int("not_a_number")
print(f"Processed value: {value}")
return 0 # Success exit code
except Exception as e:
print(f"An unexpected error occurred: {e}", file=sys.stderr)
# Use cli_exit_tools to print detailed exception message and get an appropriate exit code
cli_exit_tools.print_exception_message(trace_back=True, stream=sys.stderr)
return cli_exit_tools.get_exit_code_from_exception(e)
if __name__ == "__main__":
# In a real CLI application, you would typically call sys.exit(exit_code)
exit_code = run_cli_task()
print(f"\nApplication finished with exit code: {exit_code}", file=sys.stderr)
# sys.exit(exit_code)