Package: cli-exit-tools
cli_exit_toolsVersion v1.2.6 as of 2023-07-14 seeChangelogsmall toolset to properly exit a cli application:print the traceback information (can be set with commandline option)get a proper exit code from the Exceptionflush the streams, to make sure output is written in proper orderdemo how to integrate into Your cli module (see usage)automated tests, Github Actions, Documentation, Badges, etc. are managed withPizzaCutter(cookiecutter on steroids)Python version required: 3.8.0 or newertested on recent linux with python 3.8, 3.9, 3.10, 3.11, 3.12-dev, pypy-3.9, pypy-3.10 - architectures: amd64100% code coverage, flake8 style checking ,mypy static type checking ,tested underLinux, macOS, Windows, automatic daily builds and monitoringTry it OnlineUsageUsage from CommandlineInstallation and UpgradeRequirementsAcknowledgementsContributeReport IssuesPull RequestCode of ConductLicenseChangelogTry it OnlineYou might try it right away in Jupyter Notebook by using the “launch binder” badge, or clickhereUsageexample for the main_cli# STDLIBimportsysfromtypingimportOptional# EXTimportclick# CONSTANTSCLICK_CONTEXT_SETTINGS=dict(help_option_names=["-h","--help"])try:from.import__init__conf__from.importcli_exit_toolsexcept(ImportError,ModuleNotFoundError):# pragma: no cover# imports for doctestimport__init__conf__# type: ignore  # pragma: no coverimportcli_exit_tools# type: ignore  # pragma: no coverdefinfo()->None:"""
    >>> info()
    Info for ...

    """__init__conf__.print_info()@click.group(help=__init__conf__.title,context_settings=CLICK_CONTEXT_SETTINGS)# type: ignore@click.version_option(version=__init__conf__.version,prog_name=__init__conf__.shell_command,message=f"{__init__conf__.shell_command}version{__init__conf__.version}")@click.option("--traceback/--no-traceback",is_flag=True,type=bool,default=None,help="return traceback information on cli")defcli_main(traceback:Optional[bool]=None)->None:iftracebackisnotNone:cli_exit_tools.config.traceback=traceback@cli_main.command("info",context_settings=CLICK_CONTEXT_SETTINGS)# type: ignoredefcli_info()->None:"""get program informations"""info()# entry point if mainif__name__=="__main__":try:cli_main()# type: ignoreexceptExceptionasexc:cli_exit_tools.print_exception_message()sys.exit(cli_exit_tools.get_system_exit_code(exc))finally:cli_exit_tools.flush_streams()get the system exit codedefget_system_exit_code(exc:BaseException)->int:"""
    Return the exit code for linux or windows os, based on the exception.
    If, on windows, the winerror code is passed with the Exception, we return that winerror code.


    Parameter
    ---------
    exc
        the exception to analyze


    Result
    ------
    exit_code
        as integer


    Examples
    --------

    >>> try:
    ...     raise RuntimeError()
    ... except RuntimeError as my_exc:
    ...     assert get_system_exit_code(my_exc) == 1
    ...     setattr(my_exc, 'winerror', 42)
    ...     assert get_system_exit_code(my_exc) == 42
    ...     setattr(my_exc, 'winerror', None)
    ...     assert get_system_exit_code(my_exc) == 1
    >>> try:
    ...     exit(99)
    ... except SystemExit as my_exc:
    ...     assert get_system_exit_code(my_exc) == 99

    """print the exception messagedefprint_exception_message(trace_back:bool=config.traceback,length_limit:int=500,stream:Optional[TextIO]=None)->None:"""
    Prints the Exception Message to stderr
    if trace_back is True, it also prints the traceback information

    if the exception has stdout, stderr attributes (like the subprocess.CalledProcessError)
    those will be also printed to stderr


    Parameter
    ---------
    trace_back
        if traceback information should be printed. This is usually set early
        in the CLI application to the config object via a commandline option.
    length_limit
        int, limits the length of the message
    stream
        optional, to which stream to print, default = stderr


    Examples
    --------

    >>> # test with exc_info = None
    >>> print_exception_message()

    >>> # test with exc_info
    >>> try:
    ...     raise FileNotFoundError('unknown_command_test1')
    ... except Exception:       # noqa
    ...     print_exception_message(True, length_limit=15, stream=sys.stdout)
    ...     print_exception_message(False, stream=sys.stdout)
    ...     print_exception_message(True, stream=sys.stdout)
    Traceback Info...

    >>> # test with subprocess to get stdout, stderr
    >>> import subprocess
    >>> try:
    ...     discard=subprocess.run('unknown_command_test2', shell=True, check=True)
    ... except subprocess.CalledProcessError:
    ...     print_exception_message(False, stream=sys.stdout)
    ...     print_exception_message(True, stream=sys.stdout)
    ...     print_exception_message(True, stream=sys.stdout)
    CalledProcessError...

    """flush the streamsdefflush_streams()->None:"""
    flush the streams - make sure the output is written early,
    otherwise the output might be printed even after another CLI
    command is launched


    Examples
    --------


    >>> flush_streams()

    """Usage from CommandlineUsage: cli_exit_tools [OPTIONS] COMMAND [ARGS]...

  functions to exit an cli application properly

Options:
  --version                     Show the version and exit.
  --traceback / --no-traceback  return traceback information on cli
  -h, --help                    Show this message and exit.

Commands:
  info  get program informationsInstallation and UpgradeBefore You start, its highly recommended to update pip and setup tools:python -m pip --upgrade pip
python -m pip --upgrade setuptoolsto install the latest release from PyPi via pip (recommended):python -m pip install --upgrade cli_exit_toolsto install the latest release from PyPi via pip, including test dependencies:python -m pip install --upgrade cli_exit_tools[test]to install the latest version from github via pip:python -m pip install --upgrade git+https://github.com/bitranox/cli_exit_tools.gitinclude it into Your requirements.txt:# Insert following line in Your requirements.txt:
# for the latest Release on pypi:
cli_exit_tools

# for the latest development version :
cli_exit_tools @ git+https://github.com/bitranox/cli_exit_tools.git

# to install and upgrade all modules mentioned in requirements.txt:
python -m pip install --upgrade -r /<path>/requirements.txtto install the latest development version, including test dependencies from source code:# cd ~
$ git clone https://github.com/bitranox/cli_exit_tools.git
$ cd cli_exit_tools
python -m pip install -e .[test]via makefile:
makefiles are a very convenient way to install. Here we can do much more,
like installing virtual environments, clean caches and so on.# from Your shell's homedirectory:$gitclonehttps://github.com/bitranox/cli_exit_tools.git$cdcli_exit_tools# to run the tests:$maketest# to install the package$makeinstall# to clean the package$makeclean# uninstall the package$makeuninstallRequirementsfollowing modules will be automatically installed :## Project Requirementsclicklib_detect_testenvAcknowledgementsspecial thanks to “uncle bob” Robert C. Martin, especially for his books on “clean code” and “clean architecture”ContributeI would love for you to fork and send me pull request for this project.
-please ContributeLicenseThis software is licensed under theMIT license—Changelognew MAJOR version for incompatible API changes,new MINOR version for added functionality in a backwards compatible mannernew PATCH version for backwards compatible bug fixesv1.2.62023-07-14:add codeql badgemove 3rd_party_stubs outside the src directoryadd pypy 3.10 testsadd python 3.12-dev testsv1.2.52023-07-13:require minimum python 3.8remove python 3.7 testsv1.2.42023-07-12:introduce PEP517 packaging standardintroduce pyproject.toml build-systemremove mypy.iniremove pytest.iniremove setup.cfgremove setup.pyremove .bettercodehub.ymlremove .travis.ymlupdate black configclean ./tests/test_cli.pyv1.2.3.22022-06-02: update to github actionscheckout@v3andsetup-python@v3v1.2.3.12022-06-01: update github actions test matrixv1.2.32022-03-29: remedy mypy Untyped decorator makes function “cli_info” untypedv1.2.22022-03-25: fix github actions windows testv1.2.12021-11-22: Patch Releasefix minor readme.rst bugsremove second github action ymlfix “setup.py test”v1.2.02021-11-21: Minor Releaseimplement github actionsimplement system.exit()v1.1.82020-10-09: service releaseupdate travis build matrix for linux 3.9-devupdate travis build matrix (paths) for windows 3.9 / 3.10v1.1.72020-08-08: service releasefix documentationfix travisdeprecate pycodestyleimplement flake8v1.1.62020-08-07: fix wheelsv1.1.52020-07-31: fix wheelsv1.1.32020-07-31: initial release