如何禁用打印子命令选项,大括号之间的选项?使用http://docs.python.org/dev/library/argparse.html#sub-commands上的示例,正常输出为:
usage: [-h] {foo,bar} ...
optional arguments:
-h, --help show this help message and exit
subcommands:
{foo,bar} additional help
Run Code Online (Sandbox Code Playgroud)
我想要的是打印这个:
usage: [-h] {foo,bar} ...
optional arguments:
-h, --help show this help message and exit
subcommands:
Run Code Online (Sandbox Code Playgroud)
只删除最后一行.
为了避免使用大量丑陋的花括号列表中的几十个子命令向我的用户发送垃圾邮件,我只需设置metavar子命令对象的属性即可.我的代码看起来像:
import argparse
parser = argparse.ArgumentParser(description='Stack Overflow example')
subs = parser.add_subparsers()
subs.metavar = 'subcommand'
sub = subs.add_parser('one', help='does something once')
sub = subs.add_parser('two', help='does something twice')
parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
使用单个-h参数运行此脚本的输出是:
usage: tmp.py [-h] subcommand ...
Stack Overflow example
positional arguments:
subcommand
one does something once
two does something twice
optional arguments:
-h, --help show this help message and exit
Run Code Online (Sandbox Code Playgroud)
结果并不完全是你所说的最好的理想情况,但我认为它可能是你没有子类化argparse.ArgumentParser并覆盖你需要调整的东西的最接近的,这将是混乱的工作.
使用您自己的方法覆盖 ArgumentParser.print_usage() 来打印您想要的任何内容。如果您只想删除最后一行,请调用原始版本,捕获结果(通过将其发送到文件)并仅打印您想要的部分。
| 归档时间: |
|
| 查看次数: |
1259 次 |
| 最近记录: |