gpt4 book ai didi

python optparse,如何在使用输出中包含附加信息?

转载 作者:IT老高 更新时间:2023-10-28 22:16:52 25 4
gpt4 key购买 nike

使用 python 的 optparse 模块我想在常规使用输出下方添加额外的示例行。我当前的 help_print() 输出如下所示:

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()

最佳答案

parser = optparse.OptionParser(epilog="otherstuff")

默认的 format_epilog 会去除换行符(使用 textwrap),因此您需要像这样在解析器中覆盖 format_epilog

def main():

class MyParser(optparse.OptionParser):
def format_epilog(self, formatter):
return self.epilog

parser =MyParser(epilog=
"""Examples:

check_dell -c all
check_dell -c fans memory voltage
check_dell -s
""")
...

这里有更多细节。
如果你在 OptionParser 类中查看 optparse.py 有一个名为 format_epilog 的方法,它由 format_help 调用

这是 optparse.py 的片段

def format_epilog(self, formatter):
return formatter.format_epilog(self.epilog)

def format_help(self, formatter=None):
if formatter is None:
formatter = self.formatter
result = []
if self.usage:
result.append(self.get_usage() + "\n")
if self.description:
result.append(self.format_description(formatter) + "\n")
result.append(self.format_option_help(formatter))
result.append(self.format_epilog(formatter))
return "".join(result)

formatter.format_epilog 的默认行为是使用 textwrap.fill,其中包括从 Epilog 中删除换行符。由于我们希望保留换行符,我们将 OptionParser 子类化并更改 format_epilog

的行为

关于python optparse,如何在使用输出中包含附加信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1857346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com