Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass and parse a list of strings from command line with argparse.ArgumentParser in Python?

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!

like image 883
Fomalhaut Avatar asked May 04 '17 14:05

Fomalhaut


People also ask

What does Argparse ArgumentParser () do?

ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required .

What is Subparser?

A “subparser” is an argument parser bound to a namespace. In other words, it works with everything after a certain positional argument. Argh implements commands by creating a subparser for every function.


2 Answers

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 
like image 132
chepner Avatar answered Sep 20 '22 14:09

chepner


You need to use nargs:

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

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

like image 42
liiight Avatar answered Sep 22 '22 14:09

liiight