Nearby lessons

157 of 159

Python - Command Line Arguments

📌 What You Will Learn
  • Understand what command line arguments are and how they are passed to a program
  • Access command line arguments using the argv list from the sys module
  • Recognize that argv[0] is the program name and argv[1:] holds the arguments
  • Convert string arguments to numbers with int() for calculations
  • Handle spaces in arguments with double quotes and invalid indexes with IndexError
  • Use the argparse module for advanced command line argument parsing

Introduction

Command Line Arguments are the values passed to a Python program at the time of execution.

These values can be accessed inside the program using the argv list available in the sys module.

What is argv?

argv is a list that stores all command line arguments.

  • argv is a list, not an array.
  • It is available in the sys module.

Example - Command Line Arguments

D:\Python_classes> py test.py 10 20 30
        

Here:

  • 10
  • 20
  • 30

are the command line arguments.

Accessing Command Line Arguments

Command line arguments are available through argv in the sys module.

Import argv

🐍Code Cell
1from sys import argv
Output
No output captured.

Important Note

  • argv[0] represents the program name.
  • argv[1] represents the first command line argument.
  • argv[2] represents the second command line argument.

Program to Check the Type of argv

🐍Code Cell
1from sys import argv
2 
3print(type(argv))
Output
No output captured.

Program to Display Command Line Arguments

🐍Code Cell
1from sys import argv
2 
3print("The Number of Command Line Arguments:", len(argv))
4print("The List of Command Line Arguments:", argv)
5 
6print("Command Line Arguments one by one:")
7 
8for x in argv:
9 print(x)
Output
Execution

D:\Python_classes> py test.py 10 20 30

Output

The Number of Command Line Arguments: 4
The List of Command Line Arguments:
['test.py', '10', '20', '30']

Command Line Arguments one by one:
test.py
10
20
30

Program to Find the Sum of Command Line Arguments

🐍Code Cell
1from sys import argv
2 
3sum = 0
4args = argv[1:]
5 
6for x in args:
7 n = int(x)
8 sum = sum + n
9 
10print("The Sum:", sum)
Output
Execution

D:\Python_classes> py test.py 10 20 30 40

Output

The Sum: 100

Important Note - Space Separator

By default, command line arguments are separated by spaces.

If an argument contains spaces, it must be enclosed in double quotes.

Example 1

D:\Python_classes> py test.py Sunny Leone
        

Output

Sunny
        

Example 2

D:\Python_classes> py test.py 'Sunny Leone'
        

Output

'Sunny
        

Example 3

D:\Python_classes> py test.py "Sunny Leone"
        

Output

Sunny Leone
        

Important Note - Type Conversion

All command line arguments are stored as strings.

Use type casting to convert them into the required data type.

Example - String vs Integer

🐍Code Cell
1from sys import argv
2 
3print(argv[1] + argv[2])
4print(int(argv[1]) + int(argv[2]))
Output
Execution

D:\Python_classes> py test.py 10 20

Output

1020
30

Important Note - Invalid Index

If you try to access an index that does not exist, Python raises an IndexError.

Example - Invalid Index

🐍Code Cell
1from sys import argv
2 
3print(argv[100])
Output
Execution

D:\Python_classes> py test.py 10 20

Output

IndexError: list index out of range

argparse Module

Python provides the argparse module for advanced command line argument handling.

It is used to:

  • Parse command line arguments.
  • Display help messages when the user enters incorrect input.

Real World Usage

Command line arguments are commonly used in:

  • Automation scripts
  • System administration
  • Data processing programs
  • Backup utilities
  • Python tools and utilities

Important Notes

  • argv is a list, not an array.
  • Command line arguments are available through the sys module.
  • argv[0] contains the program name.
  • argv[1:] contains all command line arguments except the program name.
  • All command line arguments are stored as strings.
  • Use type casting such as int() and float() when required.
  • If an argument contains spaces, enclose it in double quotes.
  • Accessing an invalid index raises IndexError.
  • The argparse module provides advanced command line argument parsing.

Quick Summary

Topic Description
argv List containing command line arguments.
Module sys
argv[0] Program name.
argv[1] First command line argument.
argv[1:] All command line arguments except the program name.
Data Type String
Type Conversion Use int(), float(), etc.
Invalid Index Raises IndexError.
Advanced Parsing argparse module.
📝 Key Takeaways
  • Command line arguments are values passed to a program at the time of execution
  • argv is a list from the sys module that stores all command line arguments
  • argv[0] stores the program name and argv[1:] stores the arguments
  • All command line arguments are stored as strings, so use int() or float() to convert them
  • Arguments containing spaces must be enclosed in double quotes
  • The argparse module provides advanced command line parsing with help messages

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8