【发布时间】:2019-11-05 10:00:00
【问题描述】:
我正在编写一个新脚本,并且希望在不带任何参数的情况下调用脚本时默认调用 -h 或 --help 参数。因此,例如,如果有人调用 command_line_utility.py,那么我希望它打印您使用 command_line_utility.py -h 获得的输出。
我翻遍了文档并查看了一些示例,但所有示例都指定了默认参数值,实际上并没有让 arg parse 调用默认参数。
# Setting up Main Argument Parser
main_parser = argparse.ArgumentParser(description="A set of python web utility scripts")
main_parser.add_argument("-v",'--version', action='version', version='kuws V0.0.1')
# Setting up the main subparser
subparsers = main_parser.add_subparsers(help="Available commands found below, for more info on a command use: python command_line_utility.py <command> -h or kuws <command> -h")
"""Code below handles 'redirects' command in the main script
i.e. >python command_line_utility.py redirects or kuws redirects
"""
redirects_parser = subparsers.add_parser('redirects', argument_default='-u',
help='Allows you to trace redirects and get other information')
redirects_parser.add_argument('-u', "--url",
help='usage: python main.py redirects -u <url>; Lets you see the trace for a url', nargs='?', dest="trace_url")
当我运行文件时,实际上没有任何东西打印到命令行。没有帮助文本或错误或任何内容。
【问题讨论】:
-
您对使用普通帮助命令“-h”或“--help”时的显示满意吗?我看不出全局默认值与显示帮助有什么关系。
-
该命令将被添加到路径中,因此为了使用能力,我希望默认为 -h,因此当人们调用该命令时,他们只会看到帮助文本而不是什么。这类似于不提供参数时 git 命令的工作方式。
-
parser中的任何内容都是必需的,因此不会引发错误。在旧版本中,subparsers是必需的,现在您已经明确说明了。其他人已经表明您可以显示完整的help它没有任何命令行值。 -
我不认为
argument_default参数对你有用。通常参数的默认值是None。argument_default只是更改该值的另一种方式(对于此子解析器的所有参数)。更多时候我们在add_argument命令中使用default参数。
标签: python python-3.x argparse