0

I have a parser like this

parser = argparse.ArgumentParser()
parser.add_argument('--template', metavar='FILE', nargs=1, required=True)

and pass the arguments like this

myprog --template template.txt

But when I later check the args obtained from args = parser.parse_args() I will get

['template.txt']

Can I get the plain 'template.txt' instead? Thank you.

4

1 回答 1

5

Don't use nargs if you don't want it to be a list:

parser.add_argument('--template', metavar='FILE', required=True)

From the nargs option documentation:

Note that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.

and

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

于 2013-06-07T12:24:24.537 回答