sys.argv

Introduction

The sys.argv variable is provided by Python’s built-in sys module and is used to access command-line arguments passed to a Python script.

Command-line arguments allow users to provide input to a program when it is executed, making scripts more flexible and reusable.

sys.argv is commonly used in:

  • Automation Scripts

  • Batch Processing

  • Test Automation Frameworks

  • CI/CD Pipelines

  • Utility Programs

  • Data Processing Scripts

  • Command-Line Tools

In this tutorial, you will learn what sys.argv is, how it works, practical examples, automation testing use cases, common mistakes, and best practices.


What is sys.argv?

sys.argv is a list that stores command-line arguments passed to a Python script.

To use it, import the sys module:

import sys

Basic Syntax

import sys

print(sys.argv)

Understanding sys.argv

Suppose you have a file named:

test.py

Run it as:

python test.py hello world

Script

import sys

print(sys.argv)

Output

['test.py', 'hello', 'world']

Important Points

  • sys.argv is a list.

  • The first element (sys.argv[0]) is always the script name.

  • Remaining elements are command-line arguments.

  • All arguments are stored as strings.


Accessing Individual Arguments

Example

import sys

print("Script Name:", sys.argv[0])
print("First Argument:", sys.argv[1])
print("Second Argument:", sys.argv[2])

Command

python test.py Python Automation

Output

Script Name: test.py
First Argument: Python
Second Argument: Automation

Counting Arguments

Use len().

Example

import sys

print(len(sys.argv))

Command

python test.py one two three

Output

4

Explanation:

test.py
one
two
three

Total = 4 elements


Looping Through Arguments

Example

import sys

for argument in sys.argv:
    print(argument)

Command

python test.py apple banana mango

Output

test.py
apple
banana
mango

Ignoring Script Name

Usually, we only need user inputs.

Example

import sys

for argument in sys.argv[1:]:
    print(argument)

Output

apple
banana
mango

Numeric Arguments

All command-line arguments are strings.

Example

import sys

num1 = int(sys.argv[1])
num2 = int(sys.argv[2])

print(num1 + num2)

Command

python add.py 10 20

Output

30

Example: Calculator Using sys.argv

Script

import sys

num1 = int(sys.argv[1])
num2 = int(sys.argv[2])

print("Addition:", num1 + num2)
print("Subtraction:", num1 - num2)
print("Multiplication:", num1 * num2)

Command

python calculator.py 15 5

Output

Addition: 20
Subtraction: 10
Multiplication: 75

Handling Missing Arguments

Problem

import sys

print(sys.argv[1])

Command

python test.py

Error

IndexError: list index out of range

Solution

import sys

if len(sys.argv) > 1:
    print(sys.argv[1])
else:
    print("Argument Missing")

Real-World Example: Greeting User

Script

import sys

name = sys.argv[1]

print(f"Hello {name}")

Command

python greet.py John

Output

Hello John

Real-World Example: File Reader

Script

import sys

filename = sys.argv[1]

with open(filename, "r") as file:
    print(file.read())

Command

python reader.py data.txt

The file name is passed dynamically.


sys.argv in Selenium Automation

Example

Run tests in different browsers.

import sys

browser = sys.argv[1]

print(
    f"Executing tests in {browser}"
)

Command

python test_runner.py chrome

Output

Executing tests in chrome

Practical Selenium Example

import sys
from selenium import webdriver

browser = sys.argv[1]

if browser == "chrome":
    driver = webdriver.Chrome()

elif browser == "firefox":
    driver = webdriver.Firefox()

driver.get("https://example.com")

Run:

python test.py chrome

or

python test.py firefox

sys.argv in API Automation

Example

Pass environment names dynamically.

import sys

environment = sys.argv[1]

print(
    f"Running API tests in {environment}"
)

Command

python api_test.py staging

Output

Running API tests in staging

Useful for:

  • Dev

  • QA

  • Staging

  • Production

environments.


Common Mistakes Beginners Make

Forgetting to Import sys

Incorrect

print(sys.argv)

Error

NameError:
name 'sys' is not defined

Correct

import sys

Accessing Missing Arguments

Incorrect

print(sys.argv[5])

When only 2 arguments exist.

Error

IndexError

Correct

if len(sys.argv) > 5:
    print(sys.argv[5])

Forgetting Type Conversion

Incorrect

import sys

print(sys.argv[1] + sys.argv[2])

Command

python test.py 10 20

Output

1020

String concatenation occurs.


Correct

print(
    int(sys.argv[1])
    +
    int(sys.argv[2])
)

Output

30

Assuming Arguments Are Optional

Always validate input before using it.


Best Practices

Validate Argument Count

if len(sys.argv) < 2:

Convert Data Types Explicitly

int()
float()

Provide Helpful Error Messages

print(
    "Usage: python test.py <browser>"
)

Use Meaningful Argument Names

Examples:

chrome
staging
input.csv

Consider argparse for Complex Scripts

For advanced command-line tools:

import argparse

argparse is more powerful than sys.argv.


Advantages of sys.argv

  • Simple to use

  • Built into Python

  • Supports dynamic inputs

  • Useful for automation scripts

  • No additional libraries required


Limitations of sys.argv

  • All values are strings

  • Manual validation required

  • Limited support for complex arguments

  • Less user-friendly than argparse


sys.argv vs argparse

Feature sys.argv argparse
Built-in Yes Yes
Easy to Learn Yes Moderate
Argument Validation Manual Automatic
Help Messages No Yes
Advanced Options No Yes

Conclusion

sys.argv is a simple and powerful way to accept command-line arguments in Python. It enables scripts to receive dynamic input without modifying the source code.

Whether you’re running Selenium tests in different browsers, executing API tests in various environments, processing files, or creating automation utilities, sys.argv helps make your scripts flexible and reusable.

For simple automation scripts, sys.argv is often sufficient. For larger applications with many options, consider using the argparse module.


Frequently Asked Questions (FAQs)

What is sys.argv?

sys.argv is a list containing command-line arguments passed to a Python script.


What does sys.argv[0] contain?

It contains the script name.

Example:

test.py

Are command-line arguments strings?

Yes.

All arguments are stored as strings.


How do I get the number of arguments?

len(sys.argv)

Which module contains argv?

import sys

Key Takeaways

  • sys.argv comes from Python’s sys module.

  • It stores command-line arguments in a list.

  • sys.argv[0] contains the script name.

  • All arguments are stored as strings.

  • Use int() or float() for numeric inputs.

  • Validate argument counts before accessing them.

  • Useful for Selenium and API automation frameworks.

  • Helps create flexible and reusable scripts.

  • len(sys.argv) returns the number of arguments.

  • For advanced CLI applications, consider using argparse.