clize icon indicating copy to clipboard operation
clize copied to clipboard

[Question] Disable print(), if --help

Open Kristinita opened this issue 7 years ago • 1 comments

1. Summary

I don't understand, how I can disable print() in output, if I run command with --help or --version.

2. Example

For example, I have SashaClizePrint.py file, based on my previous questions:

"""Demo code for #38.

Variables:
    VARIABLE {bool} -- True or False
    VERSION {str} -- version number
"""

import logbook
import sys

from clize import run

VARIABLE = True

VERSION = "0.1"

LOG = logbook.Logger("summary logbook")


def clize_log_level(*, logbook_level: 'll'="NOTICE"):
    """Change log levels via command line.

    User select, which logging messages to see. See about 6 log levels here:
    https://logbook.readthedocs.io/en/stable/quickstart.html

    :param logbook_level: user select logging level
    """
    if logbook_level == "DEBUG":
        logbook.StreamHandler(sys.stdout,
                              level=logbook.DEBUG).push_application()
    elif logbook_level == "NOTICE":
        logbook.StreamHandler(sys.stdout,
                              level=logbook.NOTICE).push_application()
    elif logbook_level == "ERROR":
        logbook.StreamHandler(sys.stdout,
                              level=logbook.INFO).push_application()


def version():
    """Show version.

    For details see:
    https://clize.readthedocs.io/en/stable/dispatching.html#alternate-actions
    """
    print(VERSION)


def main():
    run(clize_log_level, alt=[version], exit=False)
    if VARIABLE:
        LOG.debug("Success!")
        print("Success!")

    else:
        LOG.error("Failure!")
        print("Failure!")


if __name__ == '__main__':
    main()

3. Command line

3.1. Expected

I want, that Success! print, if I run this file.

D:\Киролайна>python SashaClizePrint.py
[2018-01-22 10:59:34.455838] NOTICE: summary logbook: Success!
Success!
D:\Киролайна>python SashaClizePrint.py --ll=ERROR
Success!

3.2. Non-expected

But I don't want Success! in console, if I want get help or version.

D:\Киролайна>python SashaClizePrint.py --help
Usage: SashaClizePrint.py [OPTIONS]

Change log levels via command line.

User select, which logging messages to see. See about 6 log levels here: https://logbook.readthedocs.io/en/stable/quickstart.html

Options:
  --logbook-level, --ll=STR   user select logging level (default: NOTICE)

Other actions:
  -h, --help                  Show the help
  --version                   Show version.
Success!
D:\Киролайна>python SashaClizePrint.py --version
0.1
Success!

4. Argumentation

In real, I want beautiful colored output instead of print("Success!"), for example, as here.

I don't find, how I can log this output.

Thanks.

Kristinita avatar Jan 22 '18 11:01 Kristinita

I had the same itch, but actually, it's easy to just use Clize API itself.

def myrun(main):
    try:
        cli = Clize.get_cli(main)
        out = cli()
        if isinstance(out, str):
            print(out)
        sys.exit(0)
    except BrokenPipeError:
        logger.info("Exécution interronpue.")
    except pdb.bdb.BdbQuit:
        logger.info("Sortie de debuggeur.")
    except UserError as e:
        logger.critical("%s", e)
    except Exception:
        logger.exception('Erreur inconnue:')
        if sys.stderr.isatty():
            pdb.post_mortem(sys.exc_info()[2])
    sys.exit(1)

bersace avatar Apr 26 '18 15:04 bersace