Search code examples
python-3.xargparse

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?


Solution

  • 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