如何将Python Click的默认选项设置为-h?
Absolutely! You can configure your Click-based script to show the help message by default when run without any arguments. Here's how to tweak your existing code:
import click CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--toduhornot', is_flag=True, help='prints "duh..."') @click.pass_context # Inject the command context to access help functionality def duh(ctx, toduhornot): if toduhornot: click.echo('duh...') else: # Print the full help text when no flags are provided click.echo(ctx.get_help()) # Optional: Exit with a non-zero code to signal no action was taken ctx.exit(1) if __name__ == '__main__': duh()
Key changes explained:
- Added
@click.pass_context: This gives your function access to the command's context object, which includes utilities like retrieving the help message. - The
elseblock: When the--toduhornotflag isn't used, we fetch and print the help text usingctx.get_help(). - Optional exit code: The
ctx.exit(1)line is optional, but it's useful if you want to indicate to shell scripts that no actionable command was executed (a non-zero exit code is standard for this).
Testing it out:
- Run
python3 duh.pywithout any arguments: You'll see the full help message, just like if you randuh.py -h. - Run
python3 duh.py --toduhornot: It still outputs "duh..." as intended.
If you ever expand this script with more options, you could check ctx.params to see if any arguments were provided at all, but for your current single-flag setup, checking toduhornot directly is clean and straightforward.
内容的提问来源于stack exchange,提问作者alvas
相关产品推荐
相关产品推荐

