Python sys.argv Tutorial

Python Sys.argv Parse Command Line Arguments

This is a detailed tutorial on Python sys.argv. Learn to parse and read the command line arguments in your python program using the sys.argv list.

Use of sys.argv

In python, sys.argv is basically a Python List that contains command-line arguments passed to the script that is being currently executed. Command-line arguments are often helpful to take inputs from the user to the python program.

To make use of sys.argv, you first have to import the sys module into your python program. You need not explicitly install the sys module as it comes pre-installed with python. The following lines of code show that sys.argv contains a list of command-line arguments.

Python Sys.argv

Observe the following code and the output screenshot. You can clearly see it contains a list and the list currently contains only one element and that is main.py which is the name of the file which is currently being executed. So, the first argument of the list sys.argv is always the name of the file that is being executed.

Now, for the demonstration, I’ve provided three more command-line argument arg1, arg2 and arg3 to the script and you can observe in the output screenshot that the list contains these added arguments.

Python Command Line Arguments Sys.argv Example

Note. Command Line arguments are separated with space.

As sys.argv is a list, you can perform all of the operations that can be performed on any of the other python lists. I’ve listed below some of our python list tutorials.

Examples

The examples of each of these are given below.

You can traverse any particular command-line argument using indexes on the sys.argv list. Remember that sys.argv[0] will always give you the name of script that is currently being executed. Likewise sys.argv[1], sys.argv[2], sys.argv[3] and so on will give you the command line arguments according to the specified indexes.

You can simply apply the len() function on the sys.argv list to find the number of command-line arguments.

We’ve typed the following command in the console to run the above code saved in a file named main.py.

Python Command Line Arguments Parsing With Sys.argv Example

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

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