Reading Command-Line Arguments via argv

๐Ÿท๏ธ Operating System and System Operations / The sys Module

When you run a Python script from the terminal, you often need to pass information into the script at the moment of execution. This is where command-line arguments become essential. Instead of hardcoding values inside your script, you can supply them dynamically when you call the script. Python's sys module provides a simple list called argv that captures everything typed after the script name on the command line.


โš™๏ธ What is sys.argv?

The sys.argv list contains all the arguments passed to your Python script when it is executed from the terminal. The first element, sys.argv[0], is always the name of the script itself. Any additional words typed after the script name become subsequent elements in the list.

  • sys.argv[0] โ†’ The script name (e.g., script.py)
  • sys.argv[1] โ†’ The first argument after the script name
  • sys.argv[2] โ†’ The second argument after the script name
  • And so on, for as many arguments as you provide

๐Ÿ› ๏ธ How to Access Command-Line Arguments

To use sys.argv, you first need to import the sys module at the top of your script. Once imported, you can access the list directly. The number of arguments provided is given by len(sys.argv).

  • Import the module: import sys
  • Access the script name: sys.argv[0]
  • Access the first argument: sys.argv[1]
  • Check how many arguments were passed: len(sys.argv)

๐Ÿ“Š Understanding Argument Count

The length of sys.argv tells you how many items were provided on the command line. This is useful for validating that the user supplied the correct number of arguments before your script tries to use them.

Number of Arguments What sys.argv Contains Example Command
1 (only script name) ['script.py'] python script.py
2 (script + one argument) ['script.py', 'config.yaml'] python script.py config.yaml
3 (script + two arguments) ['script.py', 'server1', '8080'] python script.py server1 8080

๐Ÿ•ต๏ธ Checking for Arguments Before Use

A common practice is to check if the user provided the expected number of arguments before attempting to use them. This prevents your script from crashing with an index error if arguments are missing.

  • Use an if statement to compare len(sys.argv) against the expected count
  • If the count is too low, print a usage message and exit the script
  • If the count is correct, proceed to use the arguments

๐Ÿงช Practical Example: A Simple Greeting Script

Imagine you want a script that greets a person by name. The user would run the script like this: python greet.py Alice. Inside the script, sys.argv[1] would contain the string Alice.

  • The script checks that exactly one argument (besides the script name) was provided
  • If not, it prints a message showing the correct usage
  • If yes, it prints a greeting using the provided name

โš ๏ธ Important Notes About sys.argv

  • All arguments are stored as strings, even if they look like numbers. If you need to perform math with an argument, you must convert it using int() or float().
  • Arguments are separated by spaces on the command line. If you need to pass a value that contains spaces, enclose it in double quotes: python script.py "this is one argument"
  • The script name in sys.argv[0] may include the full path depending on how you run the script

๐ŸŽฏ Why This Matters for Everyday Scripting

Using command-line arguments makes your scripts reusable and flexible. Instead of editing the script file every time you need to change a value, you simply provide the new value when you run the script. This is especially useful for:

  • Specifying configuration files or input data paths
  • Passing server names, ports, or environment names
  • Controlling script behavior (e.g., verbose mode, dry-run mode)
  • Automating tasks where different parameters are needed each run

โœ… Summary

  • sys.argv is a list in Python's sys module that holds command-line arguments
  • The first element is always the script name, followed by any additional arguments
  • Always check the length of sys.argv before accessing elements to avoid errors
  • Remember that all arguments are strings and may need conversion for numerical operations
  • This simple mechanism gives you powerful control over how your scripts behave at runtime

The sys.argv list holds the command-line arguments passed to a Python script when it is run from the terminal.


๐Ÿ”ง Example 1: Printing all arguments including the script name

This example shows the simplest use of argv โ€” printing everything that was passed when running the script.

import sys

print(sys.argv)

๐Ÿ“ค Output: ['script.py', 'arg1', 'arg2', 'arg3']


๐Ÿ”ง Example 2: Accessing individual arguments by index

This example shows how to access specific arguments using their position in the list.

import sys

first_argument = sys.argv[0]
second_argument = sys.argv[1]
print(first_argument)
print(second_argument)

๐Ÿ“ค Output: script.py (then on next line) hello


๐Ÿ”ง Example 3: Counting how many arguments were passed

This example shows how to check the number of arguments provided by the user.

import sys

number_of_args = len(sys.argv)
print(number_of_args)

๐Ÿ“ค Output: 3 (when run as python script.py one two)


๐Ÿ”ง Example 4: Checking if a minimum number of arguments exist

This example shows how to validate that enough arguments were provided before using them.

import sys

if len(sys.argv) < 3:
    print("Error: Need at least 2 arguments")
else:
    first_arg = sys.argv[1]
    second_arg = sys.argv[2]
    print(first_arg)
    print(second_arg)

๐Ÿ“ค Output: Error: Need at least 2 arguments (when run with only 1 argument)


๐Ÿ”ง Example 5: Converting a command-line argument to a number and using it

This example shows a practical use โ€” reading a number from the command line and performing a calculation.

import sys

if len(sys.argv) < 2:
    print("Error: Please provide a number")
else:
    number = int(sys.argv[1])
    result = number * 2
    print(result)

๐Ÿ“ค Output: 10 (when run as python script.py 5)


Comparison Table

Feature sys.argv[0] sys.argv[1] and beyond
What it holds The script name User-provided arguments
Always present? Yes Only if user passed them
Typical use Not used for data Used for input values

When you run a Python script from the terminal, you often need to pass information into the script at the moment of execution. This is where command-line arguments become essential. Instead of hardcoding values inside your script, you can supply them dynamically when you call the script. Python's sys module provides a simple list called argv that captures everything typed after the script name on the command line.


โš™๏ธ What is sys.argv?

The sys.argv list contains all the arguments passed to your Python script when it is executed from the terminal. The first element, sys.argv[0], is always the name of the script itself. Any additional words typed after the script name become subsequent elements in the list.

  • sys.argv[0] โ†’ The script name (e.g., script.py)
  • sys.argv[1] โ†’ The first argument after the script name
  • sys.argv[2] โ†’ The second argument after the script name
  • And so on, for as many arguments as you provide

๐Ÿ› ๏ธ How to Access Command-Line Arguments

To use sys.argv, you first need to import the sys module at the top of your script. Once imported, you can access the list directly. The number of arguments provided is given by len(sys.argv).

  • Import the module: import sys
  • Access the script name: sys.argv[0]
  • Access the first argument: sys.argv[1]
  • Check how many arguments were passed: len(sys.argv)

๐Ÿ“Š Understanding Argument Count

The length of sys.argv tells you how many items were provided on the command line. This is useful for validating that the user supplied the correct number of arguments before your script tries to use them.

Number of Arguments What sys.argv Contains Example Command
1 (only script name) ['script.py'] python script.py
2 (script + one argument) ['script.py', 'config.yaml'] python script.py config.yaml
3 (script + two arguments) ['script.py', 'server1', '8080'] python script.py server1 8080

๐Ÿ•ต๏ธ Checking for Arguments Before Use

A common practice is to check if the user provided the expected number of arguments before attempting to use them. This prevents your script from crashing with an index error if arguments are missing.

  • Use an if statement to compare len(sys.argv) against the expected count
  • If the count is too low, print a usage message and exit the script
  • If the count is correct, proceed to use the arguments

๐Ÿงช Practical Example: A Simple Greeting Script

Imagine you want a script that greets a person by name. The user would run the script like this: python greet.py Alice. Inside the script, sys.argv[1] would contain the string Alice.

  • The script checks that exactly one argument (besides the script name) was provided
  • If not, it prints a message showing the correct usage
  • If yes, it prints a greeting using the provided name

โš ๏ธ Important Notes About sys.argv

  • All arguments are stored as strings, even if they look like numbers. If you need to perform math with an argument, you must convert it using int() or float().
  • Arguments are separated by spaces on the command line. If you need to pass a value that contains spaces, enclose it in double quotes: python script.py "this is one argument"
  • The script name in sys.argv[0] may include the full path depending on how you run the script

๐ŸŽฏ Why This Matters for Everyday Scripting

Using command-line arguments makes your scripts reusable and flexible. Instead of editing the script file every time you need to change a value, you simply provide the new value when you run the script. This is especially useful for:

  • Specifying configuration files or input data paths
  • Passing server names, ports, or environment names
  • Controlling script behavior (e.g., verbose mode, dry-run mode)
  • Automating tasks where different parameters are needed each run

โœ… Summary

  • sys.argv is a list in Python's sys module that holds command-line arguments
  • The first element is always the script name, followed by any additional arguments
  • Always check the length of sys.argv before accessing elements to avoid errors
  • Remember that all arguments are strings and may need conversion for numerical operations
  • This simple mechanism gives you powerful control over how your scripts behave at runtime

Interactive Views

You are currently in ๐Ÿ“š All-in-One mode. Use the tabs at the top to switch to ๐Ÿ“– Theory Only or ๐Ÿ’ป Code Only views.

The sys.argv list holds the command-line arguments passed to a Python script when it is run from the terminal.


๐Ÿ”ง Example 1: Printing all arguments including the script name

This example shows the simplest use of argv โ€” printing everything that was passed when running the script.

import sys

print(sys.argv)

๐Ÿ“ค Output: ['script.py', 'arg1', 'arg2', 'arg3']


๐Ÿ”ง Example 2: Accessing individual arguments by index

This example shows how to access specific arguments using their position in the list.

import sys

first_argument = sys.argv[0]
second_argument = sys.argv[1]
print(first_argument)
print(second_argument)

๐Ÿ“ค Output: script.py (then on next line) hello


๐Ÿ”ง Example 3: Counting how many arguments were passed

This example shows how to check the number of arguments provided by the user.

import sys

number_of_args = len(sys.argv)
print(number_of_args)

๐Ÿ“ค Output: 3 (when run as python script.py one two)


๐Ÿ”ง Example 4: Checking if a minimum number of arguments exist

This example shows how to validate that enough arguments were provided before using them.

import sys

if len(sys.argv) < 3:
    print("Error: Need at least 2 arguments")
else:
    first_arg = sys.argv[1]
    second_arg = sys.argv[2]
    print(first_arg)
    print(second_arg)

๐Ÿ“ค Output: Error: Need at least 2 arguments (when run with only 1 argument)


๐Ÿ”ง Example 5: Converting a command-line argument to a number and using it

This example shows a practical use โ€” reading a number from the command line and performing a calculation.

import sys

if len(sys.argv) < 2:
    print("Error: Please provide a number")
else:
    number = int(sys.argv[1])
    result = number * 2
    print(result)

๐Ÿ“ค Output: 10 (when run as python script.py 5)


Comparison Table

Feature sys.argv[0] sys.argv[1] and beyond
What it holds The script name User-provided arguments
Always present? Yes Only if user passed them
Typical use Not used for data Used for input values