Open In App

How to use sys.argv in Python

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, sys.argv is used to handle command-line arguments passed to a script during execution. These arguments are stored in a list-like object, where the first element (sys.argv[0]) is the name of the script itself and the rest are arguments provided by the user.

This feature is helpful when you want to make your Python script interactive with input provided at runtime from the command line.

What is the sys Module?

The sys module in Python provides access to some variables used or maintained by the interpreter. It includes tools to interact with the runtime environment and sys.argv is one such variable used to handle command-line arguments.

Examples of sys.argv

Example 1: Basic Use of sys.argv

Python
import sys

print("This is the name of the program:", sys.argv[0])
print("Argument List:", str(sys.argv))

Output:

sys.argv

Explanation:

  • sys.argv[0] returns the name of the script.
  • str(sys.argv) prints the list of all command-line arguments including the script name.

Use the following command to run the script:

python script_name.py arg1 arg2

Commonly Used Functions with sys.argv

Python
import sys

print("This is the name of the program:", sys.argv[0])
print("Number of elements including the name of the program:", len(sys.argv))
print("Number of elements excluding the name of the program:", len(sys.argv) - 1)
print("Argument List:", str(sys.argv))

Output:

sys.argv

Explanation:

  • len(sys.argv) gives the total number of command-line arguments.
  • len(sys.argv) - 1 gives the number of user-passed arguments excluding the script name.
  • str() helps to display the list as a readable string.

Example 2: Adding Numbers Using Command Line Arguments

Python
import sys

add = 0.0

# Get the number of command-line arguments
n = len(sys.argv)

# Start from index 1 to skip the script name
for i in range(1, n):
    add += float(sys.argv[i])

print("The sum is:", add)

Output:

sys.argv

Explanation:

  • This script accepts numeric inputs via command-line arguments.
  • Converts them to float and adds them.
  • Indexing starts from 1 to skip the script name.

Use the following command to run the script:

python script_name.py 3.5 4.2 2.3

Related articles: sys module


Next Article
Article Tags :
Practice Tags :

Similar Reads