Passing List as Command Line Argument in Python

In this tutorial, we will see how we can pass a Python list as a single argument in the command line shell of the system. We will be using the sys module to accomplish this. Let’s see more on this topic further.

  List as Command Line Argument in Python

In order to get access to the arguments passed in the command line shell in Python we use sys.argv. The arguments in sys.argv are stored in the form of an array. The first element in the array contains the name of the Python file. The following elements are the arguments passed after the name of the file.

Have a look at the given program.

import sys

for arg in sys.argv:
    print(arg)

Output:

C:\Users\Ranjeet Verma\Desktop>python args.py arg1 arg2 arg3
args.py
arg1
arg2
arg3

As you can see, sys.argv contains the file name as its first element and then the following arguments as the next elements.

Now, let’s pass a list as an argument for the same program. See the below output.

C:\Users\Ranjeet Verma\Desktop>python args.py [1,2,3,4]
args.py
[1,2,3,4]

Note: Do not give spaces while passing the list as a command line argument.

Now we want to access the individual elements and do some operation on them. How do we do it?

The following example takes a list as a command line argument and prints individual elements using a loop. See the code and its output for a better understanding.

import sys

for arg in sys.argv:
    print(arg)

l = len(sys.argv[1])

li = sys.argv[1][1:l-1].split(',')

print("The list elements are:")
for el in li:
    print(el)

Output:

C:\Users\Ranjeet Verma\Desktop>python args.py [1,2,3,4]
args.py
[1,2,3,4]
The list elements are:
1
2
3
4

Let’s try to understand the code. First, we take the list as a command line argument. We know it’s the second element (index 1) in the sys.argv array. Now we store everything from this argument in variable li except the brackets which are the first and last elements in the argument. Then we eliminate all the commas present. And hence we get the list that we can use in our program to do any kind of operation. Here, we print the elements.

Thank you and keep coding.

Also read: Python Command Line Arguments

Leave a Reply

Your email address will not be published. Required fields are marked *