Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Kristinita opened this issue Jan 22, 2018 · 1 comment
Open

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

Kristinita opened this issue Jan 22, 2018 · 1 comment

Comments

@Kristinita
Copy link

Kristinita commented Jan 22, 2018

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.

@bersace
Copy link
Contributor

bersace commented Apr 26, 2018

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants