简体   繁体   中英

Python,argparse: how to have nargs=2 with type=str and type=int

I spent some times on the argparse documentation, but I'm still struggling with this module for one option in my program:

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

I'd like to the first argument to be a string (type str ) and mandatory, while the second argument should have type int , and if no value is given have a default one (let's say default=50 ). I know how to do that when there is only one argument expected, but I have no idea how to proceed when nargs=2... Is that even possible?

You can do the following. The required keyword sets the field mandatory and the default=50 sets the default value of the option to 50 if not specified:

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

Output:

$ 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

I tend to agree with Mike's solution, but here's another way. It's not ideal, since the usage/help string tells the user to use 1 or more arguments.

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

And with that, you get:

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

I would recommend using two arguments:

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

Sorry for jumping in way late. I'd use a function for type to call.

def two_args_str_int(x):
    try:
        return int(x)
    except:
        return x

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

I had a similar problem, but "use two arguments" approach didn't work for me because I need a list of pairs: parser.add_argument('--replace', nargs=2, action='append') and if I use separate arguments then I would have to validate lengths of lists etc. Here is what I did:

  1. Use tuple for metavar to properly show help: tuple=('OLD', 'NEW') results in the help string being displayed as --replace OLD NEW . It is documented but I could not find it until tried different options.
  2. Use custom validation: after parse_args , validate the resulting list's items and call parser.error() if something is wrong. That's because they have different data types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM