86

I want to pass a list of names into my program written in Python from console. For instance, I would like to use a way similar to this (I know it shouldn't work because of bash):

$ python myprog.py -n name1 name2

So, I tried this code:

# myprog.py

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('-n', '--names-list', default=[])
args = parser.parse_args()

print(args.names_list) # I need ['name1', 'name2'] here

That led to the error:

usage: myprog.py [-h] [-n NAMES_LIST]
myprog.py: error: unrecognized arguments: name2

I know I could pass the names with quotes "name1 name2" and split it in my code args.names_list.split(). But I'm curious, is there a better way to pass the list of strings via argparse module.

Any ideas would be appreciated.

Thanks!

4 Answers 4

111

You need to define --names-list to take an arbitrary number of arguments.

parser.add_argument('-n', '--names-list', nargs='+', default=[])

Note that options with arbitrary number of arguments don't typically play well with positional arguments, though:

# Is this 4 arguments to -n, or
# 3 arguments and a single positional argument, or ...
myprog.py -n a b c d
Sign up to request clarification or add additional context in comments.

3 Comments

not possible with the --arg=value syntax? like --arg="one, two, three" or similar without splitting?
The OP already acknowledged that the string could be split after parse_args is called.
This answer misses how the parsed arguments are queried in python code.
17

You need to use nargs:

parser.add_argument('-n', '--names-list', nargs="*")

https://docs.python.org/3/library/argparse.html#nargs

1 Comment

This answer misses how the argument is called on terminal and how the parsed arguments are queried in python code.
7

Another option is to repeat the argument on the command line.

To do this, change the action to append.

parser.add_argument('-n', '--names-list', action="append")

From the terminal you can call:

python myprog.py -n name1 -n name2 -n name3

And the result will be:

Namespace(n=['name1', 'name2', 'name3'])

1 Comment

This is an elegant solution!
3
parser.add_argument('-n', '--names-list', default=[], nargs='+')

1 Comment

Please add some more information. How does the call on command line looks like? How to query the parsed arguments?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.