Sometimes you want to give your Python script information right when you run it from the terminal, without waiting for it to ask for input. This is done using command line arguments. It’s a powerful way to make your scripts more flexible and easier to automate.
🖥️ What Are Command Line Arguments?
Command line arguments are the values you type in the terminal right after the name of your script. For example, if you run your script like this: python my_script.py input.txt output.txt
, then `input.txt` and `output.txt` are the command line arguments. This is a common way to tell a program which files to work with.
📦 Accessing Arguments with the `sys` Module
To access these arguments inside your Python script, you first need to import the sys
module. The `sys` module contains a list called argv
(short for “argument vector”). This list holds all the command line arguments as strings.import sys
print(sys.argv)
🔍 Understanding the `sys.argv` List
The sys.argv
list has a specific structure. The very first element, at index 0, is always the name of the Python script itself. The actual arguments you provided follow after that. So, in our example python my_script.py input.txt output.txt
:
sys.argv[0]
would be'my_script.py'
sys.argv[1]
would be'input.txt'
sys.argv[2]
would be'output.txt'
You can check the number of arguments using len(sys.argv)
to ensure the user provided the necessary input before your program proceeds.
Using command line arguments is a standard practice for creating powerful and automatable tools. It allows your scripts to be easily integrated into larger workflows without requiring manual user interaction every time they run.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python
- How to Handle Errors Gracefully in Python with Try and Except