Understand Python sys.argv[]: Save Command Line Arguments – Python Tutorial

By | December 15, 2019

Python sys.argv can save command line arguments when run a python script. However, how to get and parse these arguments in sys.argv? To address this issue, we will write some examples for python beginners to understand.

Understand python sys.argv[]

sys.argv is a python list, which contains all arguments you want to pass into python script.

For example:

import sys


Then we can open windows command prompt to run python script.

Read More: Run Python Script in Windows 10 Command Prompt for Beginners

We can run this python script like:

python amod-test.py tutorialexample.com demo.txt

The resulta are:

<class 'list'>
['amod-test.py', 'tutorialexample.com', 'demo.txt']

From results, we can find sys.argv is a python list, which contains all arguments we have entered.

What isĀ  sys.argv[0], sys.argv[1], ….

We will print all arguments in below example.

import sys


i = 0
for argument in sys.argv:
    print("argument "+str(i) + ": "+ argument)
     i += 1

Run this python code like:

python amod-test.py

The result is:

<class 'list'>
argument 0: amod-test.py

We can find the first argument is the file name of python script.

Run this python code again like this:

python amod-test.py tutorialexample.com demo.txt

The results are:

<class 'list'>
argument 0: amod-test.py
argument 1: tutorialexample.com
argument 2: demo.txt

We will find the arguments we have entered are saved sys.argv one by one from starting the index 1.

Moreover, if you want to know how to use command line arguments in python application, you can view this tutorial.

Python Use Command Line Arguments: A Beginner Guide