Я получил сценарий со списком аргументов, определенных с Argparse. Поскольку я хочу иметь пулевые точки и разрывы в линии в тексте справки, я добавил пользовательский форматер. Это работает как обаяние, но проблема сейчас в том, что текст «использование» по умолчанию в справочнике теперь показывает объект Formatter: < /p>
usage: [-h] {list,add,remove} ...
< /code>
Если я удалю пользовательский форматер, то «использование», как и ожидалось: < /p>
usage: test.py [-h] {list,add,remove} ...
< /code>
И я не могу понять, почему и как это исправить.import argparse
class MyFormatter(argparse.ArgumentDefaultsHelpFormatter):
def __init__(self,
prog,
indent_increment=2,
max_help_position=30,
width=None):
super().__init__(self,
indent_increment=indent_increment,
max_help_position=max_help_position,
width=width)
def _split_lines(self, text, width):
"""
If the text starts with 'S|', remove the prefix, split the text into lines at the new line '\n'
and maintain spaces. Otherwise, uses the default splitting behavior of ArgumentDefaultsHelpFormatter.
"""
if text.startswith('S|'):
text = text[2:].strip().splitlines()
import textwrap
out = []
for line in text:
out.extend(textwrap.wrap(line, width))
return out
return argparse.ArgumentDefaultsHelpFormatter._split_lines(self, text, width)
parser = argparse.ArgumentParser(description="This script will do a bunch of stuff",
formatter_class=MyFormatter)
parser.set_defaults(func=lambda args: parser.print_help())
subparsers = parser.add_subparsers()
parser_list = subparsers.add_parser("list", help="Show a list of things", formatter_class=MyFormatter)
parser_add = subparsers.add_parser("add", help="Add item to the list", formatter_class=MyFormatter)
parser_add.add_argument("item", type=str, help="Item to add to the list")
parser_remove = subparsers.add_parser("remove", help="Remove item from the list", formatter_class=MyFormatter)
parser_remove.add_argument("item", type=str, help="Item to remove from the list")
args = parser.parse_args()
< /code>
Я знаю, что могу добавить свое собственное сообщение об использовании с аргументом «Использование = ', но я больше пытаюсь понять, почему использование пользовательского форматирования нарушает текст использования? < /p>
ps. Используя Python 3.12
Подробнее здесь: https://stackoverflow.com/questions/795 ... om-formatt
Python Argparse: «Использование» текст, показывающий объект Formatter при использовании пользовательского форматера ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение