Domanda

argparse in Python 2.7 per l'analisi di opzioni di input. Una delle mie opzioni è una scelta multipla. Voglio fare una lista nel suo testo di aiuto, per esempio.

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()

Tuttavia, argparse strisce tutti a capo e spazi consecutivi. Gli sguardi di risultato come

~/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

Come inserire nuove righe nel testo di aiuto?

È stato utile?

Soluzione

Prova a usare RawTextHelpFormatter :

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

Altri suggerimenti

Se si desidera solo per ignorare l'un'opzione, non si dovrebbe usare RawTextHelpFormatter. Invece sottoclasse il HelpFormatter e fornire un intro speciale per le opzioni che dovrebbero essere trattati "raw" (io 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 usarlo:

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()

Tutte le altre chiamate al .add_argument() in cui l'aiuto non inizia con R| sarà avvolto come normale.

Questa è parte della miei miglioramenti sul argparse . Lo SmartFormatter completa supporta anche l'aggiunta di le impostazioni predefinite per tutte le opzioni, e l'input grezzo della descrizione utilities. La versione completa ha il proprio metodo _split_lines, in modo che qualsiasi formattazione fatto per esempio stringhe di versione è conservata:

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

Un altro modo semplice per farlo è quello di includere textwrap .

Ad esempio,

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 ... '''))

In questo modo, si può evitare lo spazio vuoto lungo davanti ciascuna linea di uscita.

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 ...

Ho affrontato problema simile (Python 2.7.6). Ho cercato di abbattere Descrizione in diverse linee che utilizzano RawTextHelpFormatter:

parser = ArgumentParser(description="""First paragraph 

                                       Second paragraph

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

options = parser.parse_args()

E preso:

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

First paragraph 

                        Second paragraph

                        Third paragraph

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

Quindi RawTextHelpFormatter non è una soluzione. Perché la stampa descrizione come appare nel codice sorgente, conservando tutti i caratteri di spaziatura (voglio tenere d'occhio in più nel mio codice sorgente per migliorare la leggibilità, ma io non voglio stampare tutti. Anche formattatore prime non va a capo linea quando si tratta di troppo a lungo, più di 80 caratteri, per esempio).

Grazie a @Anton che hanno ispirato la giusta direzione sopra . Ma tale soluzione necessita leggera modifica per formato Descrizione .

In ogni caso, è necessario formattazione personalizzata. Ho esteso classe HelpFormatter e il metodo _fill_text overrode esistente in questo modo:

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

Confronto con il codice sorgente originale proveniente da argparse modulo:

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)

Nel codice originale tutta la descrizione viene avvolto. In formattazione personalizzata sopra tutto il testo è diviso in blocchi diversi, e ciascuno di essi è formattato in modo indipendente.

Quindi, con l'aiuto di formattazione personalizzata:

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

options = parser.parse_args()

L'output è:

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

First paragraph

Second paragraph

Third paragraph

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

ho voluto avere entrambe le interruzioni di riga manuali nel testo della descrizione, e auto avvolgimento di esso; ma nessuno dei suggerimenti qui lavorato per me - così ho finito per modificare la classe SmartFormatter fornite nelle risposte qui; i problemi con i nomi dei metodi argparse non essere un'API pubblica nonostante, qui è quello che ho (come un file chiamato 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()

Questo è come funziona in 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 partire da SmartFomatter descritto sopra, ho finito a questa soluzione:

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

Si noti che stranamente l'argomento formatter_class passato al parser di livello superiore non è inheritated da sub_parsers, uno deve passare di nuovo per ogni sub_parser creato.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top