python - Click: How to propagate the exit code back to the group - Stack Overflow

admin2025-04-17  3

I have a script which use click.group to provide sub commands. Each of the sub command might pass or fail. How do I propagate the exit code from the sub commands back to main?

import click
import sys

@click.group()
def main():
    # How do I get the exit code from `get`?
    sys.exit(0)  # use that exit code here


@mainmand()
def get():
    exit_code = 1
    # How do I send the exit code back to main?

I have a script which use click.group to provide sub commands. Each of the sub command might pass or fail. How do I propagate the exit code from the sub commands back to main?

import click
import sys

@click.group()
def main():
    # How do I get the exit code from `get`?
    sys.exit(0)  # use that exit code here


@main.command()
def get():
    exit_code = 1
    # How do I send the exit code back to main?
Share Improve this question edited Jan 31 at 21:09 Barmar 784k57 gold badges548 silver badges659 bronze badges asked Jan 31 at 18:05 Hai VuHai Vu 40.9k15 gold badges71 silver badges102 bronze badges 1
  • 1 Make it a global variable, then use sys.exit(exit_code) – Barmar Commented Jan 31 at 21:09
Add a comment  | 

1 Answer 1

Reset to default 0

After some searching and reading the source code, here is what I found.

  • In the sub (nested) commands, I don't have to send the exit code back to main. I can just exit right there and the exit code will reflect in the shell.
  • In order to do that, I need to pass around a context object and use the .exit() method. This method ensures proper clean up if required.
  • This context object must be the first parameter to the commands. It is customarily called ctx, but other names, such as context also works.

Code:

import click
import sys

@click.group()
@click.pass_context
def main(ctx: click.Context):
    pass


@main.command()
@click.pass_context
def get(ctx: click.Context):
    # In case of error
    ctx.exit(1)
转载请注明原文地址:http://anycun.com/QandA/1744852795a88531.html