Расширенная справка, основанная на группах аргументов с использованием модуля Python argparserPython

Программы на Python
Ответить
Anonymous
 Расширенная справка, основанная на группах аргументов с использованием модуля Python argparser

Сообщение Anonymous »

Рассмотрим следующий игрушечный пример:

Код: Выделить всё

cat extended_help.py

Код: Выделить всё

import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-H", "--help-all", action = "version",
help = """show extended help message (incl. advanced
parameters) and exit""",
version = "This is just a dummy implementation.")
common_args = ap.add_argument_group("common parameters",
"""These parameters are typically
enough to run the tool. `%(prog)s
-h|--help` should list these
parameters.""")
advanced_args = ap.add_argument_group("advanced parameters",
"""These parameters are for advanced
users with special needs only. To make
the help more accessible, `%(prog)s
-h|--help` should not include these
parameters, while `%(prog)s
-H|--help-all` should include them (in
addition to those included by `%(prog)s
-h|--help`.""")
common_args.add_argument("-f", "--foo", metavar = "",
help = "the very common Foo parameter")
common_args.add_argument("--flag", action = "store_true",
help = "a flag enabling a totally normal option")
advanced_args.add_argument("-b", "--bar", metavar = "",
help = "the rarely needed Bar parameter")
advanced_args.add_argument("-B", "--baz", metavar = "",
help = "the even more obscure Baz parameter")
advanced_args.add_argument("--FLAG", action = "store_true",
help = "a flag for highly advanced users only")
ap.parse_args()

Код: Выделить всё

python extended_help.py -h
печатает

Код: Выделить всё

usage: extended_help.py [-h] [-H] [-f ] [--flag] [-b ] [-B ] [--FLAG]

options:
-h, --help       show this help message and exit
-H, --help-all   show extended help message (incl. advanced parameters) and exit

common parameters:
These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters.

-f, --foo   the very common Foo parameter
--flag           a flag enabling a totally normal option

advanced parameters:
These parameters are for advanced users with special needs only. To make the help more accessible, `extended_help.py -h|--help` should not include these parameters, while
`extended_help.py -H|--help-all` should include them (in addition to those included by `extended_help.py -h|--help`.

-b, --bar   the rarely needed Bar parameter
-B, --baz   the even more obscure Baz parameter
--FLAG           a flag for highly advanced users only
в то время как

Код: Выделить всё

python extended_help.py -H
генерирует только сообщение-заполнитель

Код: Выделить всё

This is just a dummy implementation.
Как мне нужно изменить Extended_help.py, чтобы

Код: Выделить всё

python extended_help.py -h
только печать

Код: Выделить всё

usage: extended_help.py [-h] [-H] [-f ] [--flag] [-b ] [-B ] [--FLAG]

options:
-h, --help       show this help message and exit
-H, --help-all   show extended help message (incl. advanced parameters) and exit

common parameters:
These parameters are typically enough to run the tool.  `extended_help.py -h|--help` should list these parameters.

-f, --foo   the very common Foo parameter
--flag           a flag enabling a totally normal option
и иметь

Код: Выделить всё

python extended_help.py -H
воспроизвести полное справочное сообщение, напечатанное в данный момент

Код: Выделить всё

python extended_help.py -h
?
Я ищу решение, позволяющее избежать ручного дублирования справочных сообщений (сообщений определенных аргументов).

редактировать:
Я знаю, что могу заменить -H на -h следующим образом:

Код: Выделить всё

import argparse

ap = argparse.ArgumentParser(add_help = False)
ap.add_argument("-h", "--help", action = "version",
help = "show help message (common parameters only) and exit",
version = """I know I could add the entire (short) help here
but I'd like to avoid that.""")
ap.add_argument("-H", "--help-all", action = "help",
help = """show extended help message (incl. advanced
parameters) and exit""")
common_args = ap.add_argument_group("common parameters",
"""These parameters are typically
enough to run the tool. `%(prog)s
-h|--help` should list these
parameters.""")
# The rest would be the same as above.
Так,

Код: Выделить всё

python extended_help.py -H
уже работает как задумано:

Код: Выделить всё

usage: extended_help.py [-h] [-H] [-f ] [--flag] [-b ] [-B ] [--FLAG]

options:
-h, --help       show help message (common parameters only) and exit
-H, --help-all   show extended help message (incl. advanced parameters) and exit

common parameters:
These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters.

-f, --foo   the very common Foo parameter
--flag           a flag enabling a totally normal option

advanced parameters:
These parameters are for advanced users with special needs only. To make the help more accessible, `extended_help.py -h|--help` should not include these parameters, while
`extended_help.py -H|--help-all` should include them (in addition to those included by `extended_help.py -h|--help`.

-b, --bar   the rarely needed Bar parameter
-B, --baz   the even more obscure Baz parameter
--FLAG           a flag for highly advanced users only
Однако теперь

Код: Выделить всё

python extended_help.py -h
печатает только заполнитель:

Код: Выделить всё

I know I could add the entire help here but I'd like to avoid that.
обновление:
Мне удалось подобраться довольно близко:

Код: Выделить всё

import argparse

ap = argparse.ArgumentParser(add_help = False, conflict_handler = "resolve")
ap.add_argument("-h", "--help", action = "help",
help = "show help message (common parameters only) and exit")
ap.add_argument("-H", "--help-all", action = "help",
help = """show extended help message (incl. advanced
parameters) and exit""")
common_args = ap.add_argument_group("common parameters",
"""These parameters are typically
enough to run the tool.  `%(prog)s
-h|--help` should list these
parameters.""")
common_args.add_argument("-f", "--foo", metavar = "",
help = "the very common Foo parameter")
common_args.add_argument("--flag", action = "store_true",
help = "a flag enabling a totally normal option")
ap.add_argument("-h", "--help", action = "version", version = ap.format_help())
advanced_args = ap.add_argument_group("advanced parameters",
"""These parameters are for advanced
users with special needs only. To make
the help more accessible, `%(prog)s
-h|--help` should not include these
parameters, while `%(prog)s
-H|--help-all` should include them (in
addition to those included by `%(prog)s
-h|--help`.""")
advanced_args.add_argument("-b", "--bar", metavar = "",
help = "the rarely needed Bar parameter")
advanced_args.add_argument("-B", "--baz", metavar = "",
help = "the even more obscure Baz parameter")
advanced_args.add_argument("--FLAG", action = "store_true",
help = "a flag for highly advanced users only")
ap.parse_args()
Это фиксирует справочное сообщение перед добавлением дополнительных аргументов и перезаписывает строку «версия» флага -h|--help (ab-), используемую для хранения/печати краткого помогите.

Код: Выделить всё

python extended_help.py -H
уже работает как задумано, но

Код: Выделить всё

python extended_help.py -h
проглатывает все разрывы строк и пробелы из справочного сообщения:

Код: Выделить всё

usage: extended_help.py [-h] [-H] [-f ] [--flag] options: -h, --help show help message (common parameters only) and exit -H, --help-all show extended help message (incl.
advanced parameters) and exit common parameters: These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters. -f, --foo
 the very common Foo parameter --flag a flag enabling a totally normal option
обновление:
Проблема, оставшаяся в версии выше, оказалась связано со мной, злоупотребляющим действием версии. Я решил эту проблему, определив собственное действие для краткой справки («вдохновленное» реализацией действия help в самом модуле argparse).
I' Я оставлю приведенные выше шаги здесь из соображений документирования. Если хотите, не стесняйтесь исправить вопрос (или предложите мне это сделать).
Любые отзывы о моем решении или альтернативные предложения будут приветствоваться.

Подробнее здесь: https://stackoverflow.com/questions/791 ... ser-module
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»