Python argparse: Как вставить новую строку в текст справки?

dgv.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
dgv.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
316
задан Anthon 2 November 2014 в 10:52
поделиться

2 ответа

Начиная с описанного выше SmartFomatter, я остановился на этом решении:

class SmartFormatter(argparse.HelpFormatter):
    '''
         Custom Help Formatter used to split help text when '\n' was 
         inserted in it.
    '''

    def _split_lines(self, text, width):
        r = []
        for t in text.splitlines(): r.extend(argparse.HelpFormatter._split_lines(self, t, width))
        return r

Обратите внимание, что странным образом аргумент formatter_class, передаваемый парсеру верхнего уровня, не наследуется sub_parsers, его необходимо передавать снова для каждого созданного sub_parser .

1
ответ дан 23 November 2019 в 01:04
поделиться

Предисловие

Для этого вопроса, argparse.RawTextHelpFormatter полезно мне.

Теперь, я хочу совместно использовать, как я использую argparse.

я знаю, что это не может быть связано с вопросом,

, но эти вопросы были побеспокоены меня некоторое время.

, Таким образом, я хочу обменяться своим опытом, надейтесь, что это будет полезно для кого-то.

Здесь мы идем.

сторонние Модули

colorama: для изменения цвет текста: pip install colorama

Делает последовательности символа ESC ANSI (для создания цветного терминального текста и расположения курсора) работой под Примером MS Windows

import colorama
from colorama import Fore, Back
from pathlib import Path
from os import startfile, system

SCRIPT_DIR = Path(__file__).resolve().parent
TEMPLATE_DIR = SCRIPT_DIR.joinpath('.')


class FormatText:
    __slots__ = ['align_list']

    def __init__(self, align_list: list):
        self.align_list = align_list

    def __call__(self, text_list: list):
        if len(text_list) != len(self.align_list):
            raise AttributeError
        return ' '.join(f'{txt:{flag}{int_align}}' for txt, (int_align, flag) in zip(text_list, self.align_list))

    @staticmethod
    def text(msg, fore_color: Fore = Fore.GREEN, back_color: Back = ""):
        return back_color + fore_color + msg + Fore.RESET


def main(args):
    ...


if __name__ == '__main__':
    colorama.init(autoreset=True)

    from argparse import ArgumentParser, RawTextHelpFormatter

    text = FormatText.text
    format_text = FormatText([(20, '<'), (60, '<')])

    script_description = \
        '\n'.join([desc for desc in
                   [f'\n{text(f"python {Path(__file__).name} [REFERENCE TEMPLATE] [OUTPUT FILE NAME]")} to create template.',
                    f'{text(f"python {Path(__file__).name} -l *")} to get all available template',
                    f'{text(f"python {Path(__file__).name} -o open")} open template directory so that you can put your template file there.',
                    # <- add your own description
                    ]])
    arg_parser = ArgumentParser(description='CREATE TEMPLATE TOOL',
                                # conflict_handler='resolve',
                                usage=script_description, formatter_class=RawTextHelpFormatter)

    arg_parser.add_argument("ref", help="reference template", nargs='?')
    arg_parser.add_argument("outfile", help="output file name", nargs='?')
    arg_parser.add_argument("action_number", help="action number", nargs='?', type=int)
    arg_parser.add_argument('--list', "-l", dest='list',
                            help=f"example: {text('-l *')} \n"
                                 "description: list current available template. (accept regex)")

    arg_parser.add_argument('--option', "-o", dest='option',
                            help='\n'.join([format_text(msg_data_list) for msg_data_list in [
                                ['example', 'description'],
                                [text('-o open'), 'open template directory so that you can put your template file there.'],
                                [text('-o run'), '...'],
                                [text('-o ...'), '...'],
                                # <- add your own description
                            ]]))

    g_args = arg_parser.parse_args()
    task_run_list = [[False, lambda: startfile('.')] if g_args.option == 'open' else None,
                     [False, lambda: [print(template_file_path.stem) for template_file_path in TEMPLATE_DIR.glob(f'{g_args.list}.py')]] if g_args.list else None,
                     # <- add your own function
                     ]
    for leave_flag, func in [task_list for task_list in task_run_list if task_list]:
        func()
        if leave_flag:
            exit(0)

    # CHECK POSITIONAL ARGUMENTS
    for attr_name, value in vars(g_args).items():
        if attr_name.startswith('-') or value is not None:
            continue
        system('cls')
        print(f'error required values of {text(attr_name)} is None')
        print(f"if you need help, please use help command to help you: {text(f'python {__file__} -h', fore_color=Fore.RED, back_color=Back.LIGHTYELLOW_EX)}")
        exit(-1)
    main(g_args)

enter image description here

0
ответ дан 23 November 2019 в 01:04
поделиться
Другие вопросы по тегам:

Похожие вопросы: