0

I am using click framework.I want to return version and exit code when I run python hello.py --version. Currently my code is like this.

import click
def print_version(ctx, param, value):
    if not value or ctx.resilient_parsing:
        return
    click.echo('Version 1.0')
    return 1
    ctx.exit()

@click.command()
@click.option('--version', is_flag=True, callback=print_version,
              expose_value=False, is_eager=True)
def hello():
    click.echo('Hello World!')

hello()
$ python hello.py --version
    Version 1.0
    Hello World!

I am expecting an output like this:

$ python hello.py --version
    Version 1.0
    1
3
  • If you would change the code in the hello() function to click.echo(1) you will get your expected output. Is that what you were looking for? Commented Aug 5, 2020 at 18:14
  • actually I want my eager function to return an exit code. in this case, i want print_version to print the version and return and exit code without invoking hello() Commented Aug 5, 2020 at 19:14
  • I added a answer. Let me know if this helped ツ! Commented Aug 5, 2020 at 19:32

1 Answer 1

3

The mistake is that you are returning from your function before the exit statement is called. So it never gets ran. You don't need the return statement here. This code should work:

import click

def print_version(ctx, param, value):
    if not value or ctx.resilient_parsing:
        return
    click.echo('Version 1.0')
    ctx.exit(0)

@click.command()
@click.option('--version', is_flag=True, callback=print_version,
              expose_value=False, is_eager=True)

def hello():
    click.echo('Hello World!')

hello()

This will only output Version 1.0 and than will exit with the exit code 0. You can change the exit code you want to have to any you want in cox.exit(YOUR_EXIT_CODE) although you probably would want to use 0 as the exit code for this.

If you want to check the exit code you can execute your program and than run a extra command in your unix-based shell to get the exit code of the last command executed:

python3 FILE_NAME.py --version
echo $?
Sign up to request clarification or add additional context in comments.

2 Comments

How to retrieve this exit code later? When I write ctx.exit(1), it still doesnt print 1. is there a way to retrieve the exit code in a test?
Yes the exit code is normally not printed. If you want to check with which exit code a program exists just run the python code in a shell how you normally would do with python3 FILE_NAME.py --version. After it has executed type echo $? this will output the exit code of the last command executed in your shell. This should work with the most unix-based shells.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.