Jelena Lazarevic
Jelena Lazarevic

Reputation: 152

Is there a way to pass list as one of the arguments in argparse

I'm writing PySpark jobs for which I want to pass several arguments. One of them should have list of strings and also one list as well. I'm having trouble figuring out how to pass list to the list of argument.

parser = argparse.ArgumentParser(description='My pyspark job arguments')

parser.add_argument('--job', type=str, required=True, dest='job_name', help='The name of the spark job you want to run')
parser.add_argument('--res-path', type=str, required=True, dest='res_path',help='Path to the jobs resurces')
parser.add_argument('-l', '--list', action='append', required=True, help='List of list')

args = parser.parse_args()

When I pass values in CLI:

--list currency
--list RSD EUR

I want output of --list to look like this:

['currency', ['RSD', 'EUR']]

Upvotes: 1

Views: 1917

Answers (1)

chepner
chepner

Reputation: 532398

nargs lets you do something close:

parser.add_argument('--list', action='append', nargs='+')

will produce [['currency'], ['RSD', 'EUR']]. One drawback is that no positional arguments can be used immediate after --list, as they will be consumed as arguments of --list itself.

Upvotes: 3

Related Questions