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

如何让Python argparse可选参数的choices在-h帮助中显示?

解决argparse可选参数choices不显示在帮助中的问题

嗨,我懂你的困扰——argparse默认会给位置参数(比如你那个Model)自动把可选的choices显示在帮助里,但对带--的可选参数就没这么贴心。不过有两种简单办法能搞定这个问题:

方法一:手动在帮助文本里补充可选值

这是最直接的方式,你只需要修改--fd参数的help字符串,把可选选项明确列进去就行。修改后的代码如下:

import argparse

parser = argparse.ArgumentParser(description="This is a program which creates a prediction model for the boston housing dataset.")
parser.add_argument("Model", help="Choose which model you want to use for prediction.", type=str, choices=["linear_regression", "polynomial_regression"])
# 把可选值直接加到help描述里
parser.add_argument("--fd", metavar="FEEDBACK", help="Set how much feedback you want. Choices: full, immediate, weak", type=str, choices=["full", "immediate", "weak"])
args = parser.parse_args()

运行-h之后,--fd的帮助项就会清晰显示可选值,用户一眼就能看到。

方法二:自定义帮助格式化器(一劳永逸版)

如果你的程序以后可能会新增更多带choices的参数,手动改每个help太麻烦,那可以自定义一个HelpFormatter,让所有参数的choices自动显示在帮助里。代码示例:

import argparse

class CustomHelpFormatter(argparse.HelpFormatter):
    def _add_arguments(self, action_group):
        # 遍历所有参数,检查是否设置了choices
        for action in action_group._actions:
            if hasattr(action, 'choices') and action.choices is not None:
                # 把可选值追加到原有帮助文本末尾
                action.help += f" (choices: {', '.join(map(str, action.choices))})"
        # 调用父类方法完成后续处理
        super()._add_arguments(action_group)

# 创建解析器时指定使用自定义格式化器
parser = argparse.ArgumentParser(description="This is a program which creates a prediction model for the boston housing dataset.", formatter_class=CustomHelpFormatter)
parser.add_argument("Model", help="Choose which model you want to use for prediction.", type=str, choices=["linear_regression", "polynomial_regression"])
parser.add_argument("--fd", metavar="FEEDBACK", help="Set how much feedback you want.", type=str, choices=["full", "immediate", "weak"])
args = parser.parse_args()

这样不管是位置参数还是可选参数,只要设置了choices,帮助界面都会自动显示可选值,不用再手动维护每个参数的帮助文本了。

内容的提问来源于stack exchange,提问作者Lupos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:29:46