How to Pass Command Line Arguments to Your Python Script

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

Hello! I'm a gaming enthusiast, a history buff, a cinema lover, connected to the news, and I enjoy exploring different lifestyles. I'm Yaman Şener/trioner.com, a web content creator who brings all these interests together to offer readers in-depth analyses, informative content, and inspiring perspectives. I'm here to accompany you through the vast spectrum of the digital world.

Leave a Reply

Your email address will not be published. Required fields are marked *