Pergunta

estou a usar argparse no Python 2.7 Para analisar as opções de entrada. Uma das minhas opções é uma escolha múltipla. Eu quero fazer uma lista em seu texto de ajuda, por exemplo

from argparse import ArgumentParser

parser = ArgumentParser(description='test')

parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',
    help="Some option, where\n"
         " a = alpha\n"
         " b = beta\n"
         " g = gamma\n"
         " d = delta\n"
         " e = epsilon")

parser.parse_args()

No entanto, argparse Tire todas as novas linhas e espaços consecutivos. O resultado se parece

~/Downloads:52$ python2.7 x.py -h
usage: x.py [-h] [-g {a,b,g,d,e}]

test

optional arguments:
  -h, --help      show this help message and exit
  -g {a,b,g,d,e}  Some option, where a = alpha b = beta g = gamma d = delta e
                  = epsilon

Como inserir novas linhas no texto de ajuda?

Foi útil?

Solução

Tente usar RawTextHelpFormatter:

from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)

Outras dicas

Se você deseja apenas substituir a opção, não deve usar RawTextHelpFormatter. Em vez disso, subclasse o HelpFormatter e forneça uma introdução especial para as opções que devem ser tratadas "cru" (eu uso "R|rest of help"):

import argparse

class SmartFormatter(argparse.HelpFormatter):

    def _split_lines(self, text, width):
        if text.startswith('R|'):
            return text[2:].splitlines()  
        # this is the RawTextHelpFormatter._split_lines
        return argparse.HelpFormatter._split_lines(self, text, width)

E use -o:

from argparse import ArgumentParser

parser = ArgumentParser(description='test', formatter_class=SmartFormatter)

parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',
    help="R|Some option, where\n"
         " a = alpha\n"
         " b = beta\n"
         " g = gamma\n"
         " d = delta\n"
         " e = epsilon")

parser.parse_args()

Quaisquer outras chamadas para .add_argument() Onde a ajuda não começa com R| será embrulhado normalmente.

Isso faz parte de minhas melhorias no argparse. O SmartFormatter completo também suporta adicionar os padrões a todas as opções e a entrada bruta da descrição dos utilitários. A versão completa tem seu próprio _split_lines Método, para que qualquer formatação feita para EG Strings de versão seja preservada:

parser.add_argument('--version', '-v', action="version",
                    version="version...\n   42!")

Outra maneira fácil de fazer isso é incluir TextWrap.

Por exemplo,

import argparse, textwrap
parser = argparse.ArgumentParser(description='some information',
        usage='use "python %(prog)s --help" for more information',
        formatter_class=argparse.RawTextHelpFormatter)

parser.add_argument('--argument', default=somedefault, type=sometype,
        help= textwrap.dedent('''\
        First line
        Second line
        More lines ... '''))

Dessa forma, podemos evitar o longo espaço vazio na frente de cada linha de saída.

usage: use "python your_python_program.py --help" for more information

Prepare input file

optional arguments:
-h, --help            show this help message and exit
--argument ARGUMENT
                      First line
                      Second line
                      More lines ...

Eu enfrentei um problema semelhante (Python 2.7.6). Eu tentei quebrar Descrição seção em várias linhas usando RawTextHelpFormatter:

parser = ArgumentParser(description="""First paragraph 

                                       Second paragraph

                                       Third paragraph""",  
                                       usage='%(prog)s [OPTIONS]', 
                                       formatter_class=RawTextHelpFormatter)

options = parser.parse_args()

E pegou:

usage: play-with-argparse.py [OPTIONS]

First paragraph 

                        Second paragraph

                        Third paragraph

optional arguments:
  -h, --help  show this help message and exit

Então RawTextHelpFormatter não é uma solução. Porque imprime a descrição como aparece no código -fonte, preservando todos os caracteres de espaço em branco (quero manter guias extras no meu código -fonte para obter legibilidade, mas não quero imprimir todas elas. Muito tempo, mais de 80 caracteres, por exemplo).

Obrigado a @Anton que inspirou a direção certa acima de. Mas essa solução precisa de uma pequena modificação para formatar Descrição seção.

De qualquer forma, é necessário formatador personalizado. Eu estendi existente HelpFormatter classe e substituição _fill_text Método como este:

import textwrap as _textwrap
class MultilineFormatter(argparse.HelpFormatter):
    def _fill_text(self, text, width, indent):
        text = self._whitespace_matcher.sub(' ', text).strip()
        paragraphs = text.split('|n ')
        multiline_text = ''
        for paragraph in paragraphs:
            formatted_paragraph = _textwrap.fill(paragraph, width, initial_indent=indent, subsequent_indent=indent) + '\n\n'
            multiline_text = multiline_text + formatted_paragraph
        return multiline_text

Compare com o código -fonte original proveniente de argparse módulo:

def _fill_text(self, text, width, indent):
    text = self._whitespace_matcher.sub(' ', text).strip()
    return _textwrap.fill(text, width, initial_indent=indent,
                                       subsequent_indent=indent)

No código original, toda a descrição está sendo envolvida. Em formato personalizado acima, todo o texto é dividido em vários pedaços, e cada um deles é formatado de forma independente.

Então, com a ajuda de formatamento personalizado:

parser = ArgumentParser(description= """First paragraph 
                                        |n                              
                                        Second paragraph
                                        |n
                                        Third paragraph""",  
                usage='%(prog)s [OPTIONS]',
                formatter_class=MultilineFormatter)

options = parser.parse_args()

A saída é:

usage: play-with-argparse.py [OPTIONS]

First paragraph

Second paragraph

Third paragraph

optional arguments:
  -h, --help  show this help message and exit

Eu queria ter quebras de linha manual no texto da descrição e embrulho automático; Mas nenhuma das sugestões aqui funcionou para mim - então acabei modificando a classe SmartFormatter dada nas respostas aqui; Os problemas com o método argparse nomes não sendo uma API pública, apesar de test.py):

import argparse
from argparse import RawDescriptionHelpFormatter

# call with: python test.py -h

class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
  #def _split_lines(self, text, width): # RawTextHelpFormatter, although function name might change depending on Python
  def _fill_text(self, text, width, indent): # RawDescriptionHelpFormatter, although function name might change depending on Python
    #print("splot",text)
    if text.startswith('R|'):
      paragraphs = text[2:].splitlines()
      rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
      #print(rebroken)
      rebrokenstr = []
      for tlinearr in rebroken:
        if (len(tlinearr) == 0):
          rebrokenstr.append("")
        else:
          for tlinepiece in tlinearr:
            rebrokenstr.append(tlinepiece)
      #print(rebrokenstr)
      return '\n'.join(rebrokenstr) #(argparse._textwrap.wrap(text[2:], width))
    # this is the RawTextHelpFormatter._split_lines
    #return argparse.HelpFormatter._split_lines(self, text, width)
    return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)

parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Blahbla bla blah blahh/blahbla (bla blah-blabla) a blahblah bl a blaha-blah .blah blah

Blah blah bla blahblah, bla blahblah blah blah bl blblah bl blahb; blah bl blah bl bl a blah, bla blahb bl:

  blah blahblah blah bl blah blahblah""")

options = parser.parse_args()

É assim que funciona em 2.7 e 3.4:

$ python test.py -h
usage: test.py [-h]

Blahbla bla blah blahh/blahbla (bla blah-blabla) a blahblah bl a blaha-blah
.blah blah

Blah blah bla blahblah, bla blahblah blah blah bl blblah bl blahb; blah bl
blah bl bl a blah, bla blahb bl:

  blah blahblah blah bl blah blahblah

optional arguments:
  -h, --help  show this help message and exit

A partir do SmartFomatter descrito acima, terminei para essa solução:

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

Observe que, estranhamente, o argumento formatador_class passado para o analisador de nível superior não é herdado pelos sub_parsers, é preciso passá -lo novamente para cada sub_parser criado.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top