Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何仅打印ArgParse的特定参数的帮助字符串的内容_Python_Argparse - Fatal编程技术网

Python 如何仅打印ArgParse的特定参数的帮助字符串的内容

Python 如何仅打印ArgParse的特定参数的帮助字符串的内容,python,argparse,Python,Argparse,是否有方法访问参数解析器库对象的特定参数的帮助字符串 如果命令行上有该选项,我想打印帮助字符串内容。不是参数分析器可以通过ArgumentParser.print\u帮助显示的完整帮助文本 按照这些思路: parser = argparse.ArgumentParser() parser.add_argument("-d", "--do_x", help='the program will do X') if do_x: print(parser.<WHAT DO I HAVE

是否有方法访问参数解析器库对象的特定参数的帮助字符串

如果命令行上有该选项,我想打印帮助字符串内容。不是参数分析器可以通过ArgumentParser.print\u帮助显示的完整帮助文本

按照这些思路:

parser = argparse.ArgumentParser()

parser.add_argument("-d", "--do_x", help='the program will do X')

if do_x:
    print(parser.<WHAT DO I HAVE TO PUT HERE?>('do_x')
parser=argparse.ArgumentParser()
add_参数(“-d”,“--do_x”,help='程序将执行x')
如果要:
打印(解析器。('do_x')
这是必需的行为

$program-d

该程序将执行X


解析器。_option\u string\u actions
是选项字符串(
-d
-do\x
)和
Action之间的映射。help
属性保存帮助字符串

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--do_x", action='store_true',
                    help='the program will do X')
args = parser.parse_args()
if args.do_x:
    print(parser._option_string_actions['--do_x'].help)
    # OR  print(parser._option_string_actions['-d'].help)

parser.\u actions
Action
对象的列表。您还可以在创建解析器时获取对象

a=parser.add_argument(...)
...

If args.do_x:
      print a.help

在交互式会话中玩
argparse
。从这样一个作业中看
a

那么你是否只想打印
只要解析参数
-d
,程序就会执行X
?或者什么?谢谢你的回答,@falsetru中的一个对我来说似乎更简单,但我想这只是我的问题样式有些人不喜欢使用
属性。但他们也抱怨
a=parser…
也没有文档记录。我同意,最好将它作为函数放在API中。parser.\u option\u string\u actions['--do\u x'].help看起来更容易解释,我们不需要创建额外的变量。但是硬编码文本字符串总是很脆弱(+国际化!)。因此,从另一方面来说,a=parser…方法可能更健壮。