Skip to content

[Python] How to "argparse" package to Pass "List" Data To Program Via Terminal

Last Updated on 2021-08-13 by Clay

When we are using python to develop the backend program, we usually use argparse package to pass some arguments to python program, then we a write a shell script to make our program to be a pipeline.

Today, I want to record how to pass a List data, If we used the following program (named test.py) to pass arguments:

# coding: utf-8
import argparse


# Argument
parser = argparse.ArgumentParser()
parser.add_argument('--list_data', type=int)
args = parser.parse_args()


print('Results:', args.list_data)



Then I use the following command via terminal:

python3 test.py --list_data 1 2 3 4 5


Output:

usage: test.py [-h] [--list_data LIST_DATA]
test.py: error: unrecognized arguments: 2 3 4 5

We will got these error message.


How To Pass "List" Data

Basically, just add a parameter like nargs="+" to add_argument(). But still be careful, set the type of the specified data type to List.

The following is the correct demonstration:

# coding: utf-8
import argparse


# Argument
parser = argparse.ArgumentParser()
parser.add_argument('--list_data', type=int, nargs='+')
args = parser.parse_args()


print('Results:', args.list_data)



Then use the following command:

python3 test.py --list_data 1 2 3 4 5

Output:

Results: [1, 2, 3, 4, 5]

On the contrary, what if we set type=list easily? (…I did it at the beginning)

# coding: utf-8
import argparse


# Argument
parser = argparse.ArgumentParser()
parser.add_argument('--list_data', type=list, nargs='+')
args = parser.parse_args()


print('Results:', args.list_data)



Then enter the following command:

python3 test.py --list_data 1 2 3 4 5

Output:

Results: [['1'], ['2'], ['3'], ['4'], ['5']]

That's right, all the elements in the list have also become the data type of the List! I think this should not be the desired result.


References


Read More

Leave a ReplyCancel reply

Exit mobile version