You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 else block: When the --toduhornot flag isn't used, we fetch and print the help text using ctx.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.py without any arguments: You'll see the full help message, just like if you ran duh.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:15:50