cli-exit-tools

1.2.7 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `cli_exit_tools` to gracefully handle an exception within a simulated CLI task. It shows how to print a detailed exception message, including traceback, to `stderr` and obtain a proper exit code from the exception, which can then be used with `sys.exit()`.

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)

view raw JSON →