python 为argparse定制帮助格式化程序的最佳方法是什么,ArgumentParser

bzzcjhmw  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(102)

我正在使用argparse.ArgumentParser来解析参数和输出帮助文本。我想显示所有选项的默认值,并设置输出的宽度。我目前的解决方案似乎有点笨拙。有人能建议一个更好的方法来实现这个目的吗?我目前的方法是定义argparse.ArgumentDefaultsHelpFormatter的子类,然后修改__init__中的width属性。有没有更干净的方法?

# help class to set width of help to wrap at terminal width
class MyHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
    columns = -1

    def __init__(self, *args, **kwargs):
        if MyHelpFormatter.columns == -1:
            try:
                MyHelpFormatter.columns = os.get_terminal_size().columns
                if 'width' not in kwargs:
                    kwargs['width'] = MyHelpFormatter.columns
            except OSError:
                # not in a terminal
                pass
        super().__init__(*args, **kwargs)

# instantiate argument parser
parser = argparse.ArgumentParser(description='program description',
                                 formatter_class=MyHelpFormatter)
szqfcxe2

szqfcxe21#

最后,由于冗长,我创建了一个名为www.example.com的简单python文件argparser.py(注意多出的“r”),将其放在python路径中,现在我只使用该路径代替argparse。

'''
Extension to argparse to show default values for arguments and
print out help at proper width on screen.  Basically, it just adds the
MyHelpFormatter to the constructor for the argparse.ArgumentParser
class.

Example usage:
-------------------
import argparser

parser = argparser.ArgumentParser(description="Find and deal with autosave file")
parser.add_argument('-n', '--newer', type=int, default=0, help='how many days back to go, 0->forever')
args = parser.parse_args()
-------------------

Running this with -h would produce:

usage: <progname>.py [-h] [-n NEWER]

Find and deal with autosave file

optional arguments:
  -h, --help            show this help message and exit
  -n NEWER, --newer NEWER
                        how many days back to go, 0->forever (default: 0)

'''

import argparse
import os
import sys

if sys.version_info[0] < 3:
    raise RuntimeError('Need python3 or greater to use argparser.py')

class MyHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
    columns = -1

    def __init__(self, *args, **kwargs):
        if MyHelpFormatter.columns == -1:
            try:
                MyHelpFormatter.columns = os.get_terminal_size().columns
                if 'width' not in kwargs:
                    kwargs['width'] = MyHelpFormatter.columns
            except OSError:
                # not in a terminal
                pass
        super().__init__(*args, **kwargs)

class ArgumentParser(argparse.ArgumentParser):
    def __init__(self, *args, **kwargs):
        kwargs['formatter_class'] = MyHelpFormatter
        super().__init__(*args, **kwargs)

相关问题