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?
After some searching and reading the source code, here is what I found.
.exit()
method. This method ensures proper clean up if required.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)
sys.exit(exit_code)
– Barmar Commented Jan 31 at 21:09