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

如何在Python的argparse中隐藏-h/--help参数?

如何隐藏argparse默认的-h/--help参数?

有两种常用方法可以实现这个需求:

方法一:创建解析器时禁用自动添加帮助参数

直接在初始化ArgumentParser时设置add_help=False,这样解析器就不会自动生成-h/--help参数:

import argparse

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-t", "--test", help=argparse.SUPPRESS)
parser.parse_args()

效果:此时输入-h或--help会触发参数错误,因为该参数已不存在。

方法二:保留帮助功能但隐藏参数条目

如果需要保留用户输入-h时显示帮助的功能,但不想让-h/--help出现在帮助菜单里,可以手动替换默认的帮助参数,并使用argparse.SUPPRESS隐藏它:

import argparse

parser = argparse.ArgumentParser()
# 覆盖默认的help参数,用SUPPRESS隐藏其在帮助菜单中的显示
parser.add_argument("-h", "--help", action="help", help=argparse.SUPPRESS)
parser.add_argument("-t", "--test", help=argparse.SUPPRESS)
parser.parse_args()

效果:用户输入-h仍能正常显示帮助内容,但帮助菜单里不会列出-h/--help的参数说明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:54:23