2013-06-06 16 views
8

li spendo alcune volte sulla documentazione argparse, ma sto ancora alle prese con questo modulo per un'opzione nel mio programma:Python, argparse: come avere nargs = 2 con type = str e il tipo = int

parser.add_argument("-r", "--rmsd", dest="rmsd", nargs=2, 
    help="extract the poses that are close from a ref according RMSD", 
    metavar=("ref","rmsd")) 

Mi piacerebbe precisare che il primo argomento è una stringa (type = str) e obbligatorio, mentre il secondo argomento è type = int, e se non viene dato alcun valore ne ha uno predefinito (diciamo default = 50) . So come farlo quando c'è un solo argomento previsto, ma non ho idea di come procedere quando nargs = 2 ... è possibile?

Molte grazie,

risposta

0

mi consiglia di utilizzare due argomenti:

import argparse 

parser = argparse.ArgumentParser(description='Example with to arguments.') 

parser.add_argument('-r', '--ref', dest='reference', required=True, 
        help='be helpful') 
parser.add_argument('-m', '--rmsd', type=int, dest='reference_msd', 
        default=50, help='be helpful') 

args = parser.parse_args() 
print args.reference 
print args.reference_msd 
8

È possibile effettuare le seguenti. Il required parola chiave imposta il campo obbligatorio e il default=50 imposta il valore predefinito dell'opzione di 50 se non specificato:

import argparse 

parser = argparse.ArgumentParser() 

parser.add_argument("-s", "--string", type=str, required=True) 
parser.add_argument("-i", "--integer", type=int, default=50) 

args = parser.parse_args()  
print args.string 
print args.integer 

uscita:

$ python arg_parser.py -s test_string 
    test_string 
    50 
$ python arg_parser.py -s test_string -i 100 
    test_string 
    100 
$ python arg_parser.py -i 100 
    usage: arg_parser.py [-h] -s STRING [-i INTEGER] 
    arg_parser.py: error: argument -s/--string is required 
5

tendo a concordare con la soluzione di Mike, ma qui è un altro modo. Non è l'ideale, dal momento che la stringa di utilizzo/aiuto dice all'utente di utilizzare 1 o più argomenti.

import argparse 

def string_integer(int_default): 
    """Action for argparse that allows a mandatory and optional 
    argument, a string and integer, with a default for the integer. 

    This factory function returns an Action subclass that is 
    configured with the integer default. 
    """ 
    class StringInteger(argparse.Action): 
     """Action to assign a string and optional integer""" 
     def __call__(self, parser, namespace, values, option_string=None): 
      message = '' 
      if len(values) not in [1, 2]: 
       message = 'argument "{}" requires 1 or 2 arguments'.format(
        self.dest) 
      if len(values) == 2: 
       try: 
        values[1] = int(values[1]) 
       except ValueError: 
        message = ('second argument to "{}" requires ' 
           'an integer'.format(self.dest)) 
      else: 
       values.append(int_default) 
      if message: 
       raise argparse.ArgumentError(self, message)    
      setattr(namespace, self.dest, values) 
    return StringInteger 

E con questo, si ottiene:

>>> import argparse 
>>> parser = argparse.ArgumentParser(description="") 
parser.add_argument('-r', '--rmsd', dest='rmsd', nargs='+', 
...       action=string_integer(50), 
...       help="extract the poses that are close from a ref " 
...       "according RMSD") 
>>> parser.parse_args('-r reference'.split()) 
Namespace(rmsd=['reference', 50]) 
>>> parser.parse_args('-r reference 30'.split()) 
Namespace(rmsd=['reference', 30]) 
>>> parser.parse_args('-r reference 30 3'.split()) 
usage: [-h] [-r RMSD [RMSD ...]] 
: error: argument -r/--rmsd: argument "rmsd" requires 1 or 2 arguments 
>>> parser.parse_args('-r reference 30.3'.split()) 
usage: [-h] [-r RMSD [RMSD ...]] 
: error: argument -r/--rmsd: second argument to "rmsd" requires an integer 
+0

Grazie per le vostre risposte, mi piacerà di evitare di creare il maggior numero opzione come ho argomento, ma penso che sia il modo più semplice in effetti ! – Bux31

Problemi correlati