straumle
straumle

Reputation: 135

Python3 argparse nargs="+" get number of arguments

I'm now googling for quite a while and I just don't find any solution to my problem.

I am using argparse to parse some command line arguments. I want to be able to parse an arbitrary number of arguments > 1 (therefore nargs="+") and I want to know afterwards how many arguments I have parsed. The arguments are all strings. But I get a problem when I just have one argument, because then the length of the list is the number of characters of the word and not 1 as in 1 argument. And I want to know how many arguments were parsed. Does anyone know how I could solve this problem?

examples:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("--test", type=str, nargs="+", required=False, default="hi")
args = parser.parse_args()
test = args.test

print(test)
print(len(test))

So with python3 example.py --test hello hallo hey the output is:

['hello', 'hallo', 'hey']
3

But with python3 example.py --test servus the output is:

servus
6

What I already know is that I could do print([test]) but I only want to do that if I have 1 argument. Because if I have more than one arguments and use print([test]) I get a double array... So I just want to know the number of parsed arguments for "test".

I cannot imagine that I am the only one with such a problem, but I could not find anything in the internet. Is there a quick and clean solution?

Upvotes: 2

Views: 4221

Answers (3)

s-jevtic
s-jevtic

Reputation: 61

Another solution (in case someone, for some reason, needs the default not to be a list): you could first check if the argument is a list, then get len if it is. For example:

if type(test) == list:
    print(len(test))

Upvotes: 0

hpaulj
hpaulj

Reputation: 231375

You left off the test=args.test line.

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("--test", type=str, nargs="+", required=False, default="hi")
args = parser.parse_args()
print(args)
print(len(args.test))

test cases

0856:~/mypy$ python3 stack68020846.py --test one two three
Namespace(test=['one', 'two', 'three'])
3
0856:~/mypy$ python3 stack68020846.py --test one
Namespace(test=['one'])
1
0856:~/mypy$ python3 stack68020846.py 
Namespace(test='hi')
2

change the default to default=[]

0856:~/mypy$ python3 stack68020846.py 
Namespace(test=[])
0

Upvotes: 2

mnikley
mnikley

Reputation: 1645

Theres probably a better solution, but try this:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("--test", type=str, nargs="+", required=False, default="hi")
args = parser.parse_args()

print("Number of arguments:", len(args._get_kwargs()[-1][-1]))

By the way, i figured this out by checking the content of args with print(dir(args))

Upvotes: 0

Related Questions