使用python的optparse模块,我想在常规用法输出下面添加额外的示例行。我当前的帮助输出如下:
usage: check_dell.py [options]
options:
-h, --help show this help message and exit
-s, --storage checks virtual and physical disks
-c, --chassis checks specified chassis components
我希望它包括在我的工作中为不太懂*nix的用户提供的使用示例。像这样的:
usage: check_dell.py [options]
options:
-h, --help show this help message and exit
-s, --storage checks virtual and physical disks
-c, --chassis checks specified chassis components
Examples:
check_dell -c all
check_dell -c fans memory voltage
check_dell -s
我该怎么做?什么样的optparse选项允许这样做?当前代码:
import optparse
def main():
parser = optparse.OptionParser()
parser.add_option('-s', '--storage', action='store_true', default=False, help='checks virtual and physical disks')
parser.add_option('-c', '--chassis', action='store_true', default=False, help='checks specified chassis components')
(opts, args) = parser.parse_args()
默认的
format_epilog
将删除换行符(使用textwrap),因此您需要这样覆盖解析器中的format_epilog
。这里有更多细节。
如果您在类
optparse.py
中查找OptionParser
,则有一个名为format_epilog
的方法,该方法由format_help
调用这是optparse.py中的片段
formatter.format_epilog
的默认行为是使用textwrap.fill
,其中包括从epilog中除去新行。因为我们希望保留新行,所以我们将OptionParser
划分为子类,并改变format_epilog
的行为使用
usage
参数:您可以通过添加更多内容(仅举一个例子):
示例输出:
看看here。
在详细说明胜出的答案(这有助于我在自己的代码中解决相同的问题)时,一个快速而肮脏的选项是直接用一个identity方法重写类的方法:
以逐字打印帮助文本。
不过,我认为这会覆盖程序中OptionParser类的所有用法的epilog格式,因此所有这样的epilog都必须在程序的其他地方使用OptionParser时逐字传递。
相关问题 更多 >
编程相关推荐