有没有办法使用 python argparse 在描述文本之后打印用法文本?我的命令行 argparse 正在工作,但我想在使用信息之前打印版本信息。
编辑:
version: 1.0
usage: blahcmd [-h] [-help]
some lovely help
argparse
模块不提供任何添加“序言”的选项。显示帮助时,它始终以usage:
开头。您能做的最好的事情就是在实例化 usage
时使用
ArgumentParser
参数来自定义添加版本号的使用文本:
import argparse
parser = argparse.ArgumentParser(usage='Any text you want\n')
请注意,帮助仍以
usage:
开头。
一个可能有效的肮脏解决方法是用
usage
:开始
\r
消息
>>> import argparse
>>> usage = '\r{}\nusage: %(prog)s etc.'.format('Version a b'.ljust(len('usage:')))
>>> parser = argparse.ArgumentParser(usage=usage)
>>> parser.parse_args(['-h'])
Version a b
usage: etc.
optional arguments:
-h, --help show this help message and exit
我不认为
\r
的这种用法是可移植的。可能有一些终端这个技巧不起作用。我已经对版本字符串进行了 ljust
编辑,以确保当该技巧起作用时,整个 usage:
字符串会从字符串中消失,并且在使用短版本字符串时,您不会得到像 v1.2e:
这样的东西。
注意:您现在必须手动创建整个
usage
文本。
这是一个丑陋的黑客(请参阅我对原始问题的评论):
定义您自己的
HelpFormatter
子类,以使用 formatter_class
选项传递给解析器。子类可能应该重写 _format_usage
方法。不完全推荐这样做,因为用于定义您自己的格式化类的接口从未公开过。
from argparse import ArgumentParser, HelpFormatter
from gettext import gettext as _
class VersionedHelp(HelpFormatter):
def _format_usage(self, usage, actions, groups, prefix=None):
if prefix is None:
prefix = _('Version: x.y\n\nusage: ')
return HelpFormatter._format_usage(self, usage, actions, groups, prefix)
p = ArgumentParser(formatter_class=VersionedHelp)
p.parse_args()
一个粗略的解决方案是将版本文本添加到您的使用行中。它并不完美(请注意额外的“用法”文本),但它是一个开始
In [64]: parser=argparse.ArgumentParser(description='description')
# 'usage' parameter just sets the 'usage' attribute
In [67]: parser.usage='version 1.0.1\n'+parser.format_usage()
In [68]: parser.print_help()
usage: version 1.0.1
usage: ipython [-h]
description
optional arguments:
-h, --help show this help message and exit
help
中组件的顺序由ArgumentParser.format_help
方法确定(引用自argparse.py
文件):
def format_help(self):
formatter = self._get_formatter()
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
# positionals, optionals and user-defined groups
for action_group in self._action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(self.epilog)
# determine help from format above
return formatter.format_help()
我可以想象编写一个自定义方法来添加您的版本信息,例如
def format_help(self):
formatter = self._get_formatter()
# version info
formatter.add_text('version 1.0.1')
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
...
在
ipython
中此功能有效:
In [74]: def format_help(parser):
formatter=parser._get_formatter()
formatter.add_text('version 1.0.1')
formatter.add_usage(parser.usage, parser._actions, parser._mutually_exclusive_groups)
formatter.add_text(parser.description)
return formatter.format_help()
In [75]: print format_help(parser)
version 1.0.1
usage: ipython [-h]
description
以下解决方案也适用于我也想在不带参数调用时以及解析以异常结束时打印帮助消息的情况。所以我消耗了解析的标准输出并再次弥补
import io
from contextlib import redirect_stdout
try:
_null=io.StringIO()
with redirect_stdout(_null):
ARG=parser.parse_args(sysy.argv[1:] or ["--help"])
except:
print("This program normally does something incredible but you got it wrong!")
parser.print_help()
sys.exit(-1)