Command Line Arguments in Python: sys.argv, argparse Guide
By upGrad
Updated on Jul 23, 2026 | 6 min read | 1.43K+ views
Share:
All courses
Certifications
More
By upGrad
Updated on Jul 23, 2026 | 6 min read | 1.43K+ views
Share:
Table of Contents
Key Takeaway
This blog walks you through everything you need. You'll learn what these arguments are, how sys.argv works, when to switch to argparse, and how to fix the errors that trip up almost every beginner.
Explore upGrad's Machine Learning programs to build practical skills in Python programming, command-line scripting, debugging, exception handling, software development, automation, and AI-powered application development through hands-on projects and industry-focused learning.
Popular upGrad Programs
You may wonder what is command line arguments in python ? A command line argument is a value you pass to a Python script from your terminal or command prompt. You type the script name, then add extra words or numbers after it. Python reads those extra words as input.
Why does this matter? Because it separates your code from your data. You don't need to open the file and edit a variable every time you want a different result. You just change what you type.
Developers use command line arguments constantly:
Here's a simple mental picture. You run a command. The terminal hands that command's extra words to Python. Python stores them somewhere it can read. You use them however you like.
Not every script needs this. A one-off script you run once doesn't. But anything you'll run repeatedly, with different inputs, benefits from it.
Think about a script that resizes images. Without arguments, you'd edit the file path inside the code every single time. With arguments, you just type a new path each run.
The following example demonstrates how to accept and use command line arguments in Python with the sys.argv module.
Python Script (greet.py)
import sys
# Check whether a name was provided
if len(sys.argv) < 2:
print("Usage: python greet.py <name>")
else:
name = sys.argv[1]
print(f"Hello, {name}! Welcome to Python.")
Run the Script
python greet.py Alice
Output
Hello, Alice! Welcome to Python.
Example with Multiple Command Line Arguments
import sys
if len(sys.argv) != 3:
print("Usage: python calculator.py <num1> <num2>")
else:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
print("Addition:", num1 + num2)
print("Subtraction:", num1 - num2)
print("Multiplication:", num1 * num2)
print("Division:", num1 / num2)
Run the Script
python calculator.py 20 10
Also Read: Simple Guide to Build Recommendation System Machine Learning
Output
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2.0
How It Works
Code |
Purpose |
| import sys | Imports the sys module. |
| sys.argv[0] | Stores the script name (calculator.py). |
| sys.argv[1] | Reads the first command line argument (20). |
| sys.argv[2] | Reads the second command line argument (10). |
| int() | Converts the string arguments into integers before performing calculations. |
This example shows how passing command line arguments in Python allows the same script to work with different inputs without modifying the source code.
Explore upGrad's Executive Diploma in Machine Learning & AI with IIIT Bangalore to build practical skills in Python programming, SQL, machine learning, deep learning, MLOps, Generative AI, Agentic AI, model deployment, and end-to-end AI application development through 30+ hands-on projects and industry-focused learning.
Recommended Courses to upskill
Explore Our Popular Courses for Career Progression
Getting started takes about two minutes. Open your terminal, navigate to your script's folder, and run it with extra words after the filename.
python script.py hello world
That's the basic pattern. hello and world are your arguments. Python doesn't do anything with them automatically though. You have to write code that reads them.
There are two common ways to do this in Python. The built-in sys module gives you raw access. The argparse module gives you a structured, validated way to handle them. We'll cover both.
The pattern always looks like this:
python <filename.py> <argument1> <argument2> ...
Order matters here, and spacing separates each value. If your value has a space in it, you'll need quotes, and we'll get to that shortly.
Learn why Python is so popular among developers.
The sys module is part of Python's standard library. No installation needed. Import it, and you're accessing command line arguments in Python within seconds.
import sys
print(sys.argv)
Run this with python script.py apple banana, and you'll see a list: ['script.py', 'apple', 'banana']. Notice the first item. It's always the script's own name. Every argument after that is what you actually typed.
sys.argv is just a list of strings. Nothing more.
That last point trips up a lot of beginners. Typing python script.py 5 doesn't give you the integer 5. It gives you the string '5'. You need int(sys.argv[1]) to convert it.
import sys
name = sys.argv[1]
print(f"Hello, {name}!")
Run python greet.py Alex, and you get Hello, Alex!. Simple enough, right? But this simplicity has a cost, and that cost shows up the moment something goes wrong.
Also Read: 25+ Selenium Projects Guide: Learn Testing with Examples
Problem |
Cause |
Solution |
| IndexError | Script expects an argument that wasn't passed | Check len(sys.argv) before accessing an index |
| Wrong data type | Values are strings by default | Convert manually using int() or float() |
| Too many or too few arguments | No built-in validation | Add manual checks or switch to argparse |
This is the real limitation of using command line arguments in Python through sys.argv alone. There's no help message. There's no automatic error handling. You're on your own for validation, and for anything beyond a handful of simple scripts, that gets tedious fast.
Also Read: Conditional Statements in Python: Hidden Logic for Smart Decisions
How to use argparse in python? argparse exists because sys.argv runs out of steam quickly. Once your script needs more than one or two inputs, or needs optional flags, or needs to explain itself to a user, argparse takes over.
It's also part of Python's standard library. Nothing extra to install.
import argparse
parser = argparse.ArgumentParser(description="A simple greeting script")
parser.add_argument("name", help="Name of the person to greet")
args = parser.parse_args()
print(f"Hello, {args.name}!")
Run this with python greet.py Alex, and it behaves just like the sys.argv version. But try running it with no arguments at all. argparse prints a clear error and a usage hint automatically. That's the difference.
Positional |
Optional |
| Required by default | Skippable, has a default value |
| No dashes needed | Uses -- or - prefix |
| Order matters | Order doesn't matter |
| Example: name | Example: --verbose |
Also Read: Iris Dataset Classification Project Using Python
Adding an optional argument is straightforward:
parser.add_argument("--greeting", default="Hello", help="Custom greeting word")
Now python greet.py Alex --greeting Hi prints Hi, Alex!. Skip the flag entirely, and it falls back to Hello. That fallback behavior is what makes optional arguments so useful for accepting command line arguments in Python without forcing users to type everything every time.
You can mark an optional-style argument as required too.
parser.add_argument("--output", required=True, help="Output file path")
Skip --output, and argparse stops the script with an error message telling you exactly what's missing. Compare that to sys.argv, where a missing value just crashes with an unhelpful IndexError.
Also Read: Data Visualization in Python
Need several values under one flag? Use nargs.
parser.add_argument("--files", nargs="+", help="List of file paths")
Now python script.py --files a.txt b.txt c.txt gives you a list of three file names. Want automatic type conversion? Add type=int or type=float to any add_argument() call, and argparse handles the conversion for you. No manual casting required.
Run any argparse script with -h or --help, and you get a formatted summary of every argument, its purpose, and whether it's required. You wrote none of that text yourself. argparse built it from your add_argument() calls.
Also Read: 4 Built-in Data Structures in Python: Dictionaries, Lists, Sets, Tuples
Here's where most beginners land on a decision. Which one should you actually use?
Feature |
sys.argv |
argparse |
| Learning curve | Very low | Slightly higher |
| Validation | None built-in | Automatic |
| Help messages | None | Auto-generated |
| Optional arguments | Manual coding needed | Native support |
| Best use case | Tiny, throwaway scripts | Anything reused or shared |
If you're writing a five-line script for yourself, sys.argv works fine. Don't overthink it. But the moment your script gets shared with a teammate, or runs on a schedule, or takes more than one or two inputs, argparse pays for itself.
Also Read: Python JSON – How to Convert a String to JSON
Two situations catch beginners off guard almost every time. Let's cover both.
Type python script.py New York and Python treats New and York as two separate arguments, not one. To keep them together, wrap the value in quotes.
python script.py "New York"
Now sys.argv[1] gives you the full string New York as a single value.
Also Read: Top Machine Learning APIs for Data Science Projects in 2026
You already saw this with argparse using nargs="+". With plain sys.argv, you'd loop over everything after index 0.
values = sys.argv[1:]
That slice grabs every argument except the script name itself. Simple, but you'll need to loop through it and convert types manually if needed.
Also Read: Module and Package in Python
This error shows up constantly, and it's almost always one of three things.
The fix is usually quick. Double check your spelling first. Then confirm every argument you're passing actually has a matching add_argument() call in your parser. Run the script with --help to see exactly what's expected, and compare that against what you typed.
Also Read: 16+ Essential Python String Methods You Should Know
A few habits separate messy scripts from ones people can actually reuse.
None of this is complicated. It's mostly about not skipping the boring parts, because those boring parts are exactly what breaks at 2 a.m. when a cron job fails silently.
Learning command line arguments in Python opens the door to writing scripts that are reusable, flexible, and much easier to automate.
For simple programs, sys.argv offers a quick way to read values passed from the terminal. Once your scripts begin accepting optional parameters, default values, or several inputs, argparse becomes the better choice because it handles parsing, validation, and help messages with very little code.
Start small. Experiment with a few scripts that accept filenames or numbers from the command line. As you gain confidence, you'll find yourself building command-line tools that are cleaner, more reliable, and easier to use in real-world projects.
Ready to start your journey? Book a free consultation with upGrad today to find the best path for your career.
Yes. While sys.argv is the simplest way to start accessing command line arguments in Python, it's not the only option. The argparse module provides a higher-level interface for parsing arguments, validating input, creating help messages, and handling errors automatically. It's the preferred choice for scripts that accept several inputs or optional flags.
Open Command Prompt, PowerShell, Terminal, or another shell, navigate to the folder containing your script, and run it using python script.py argument1 argument2. The operating system passes those values to your program in the same order they were entered, making passing command line arguments in Python consistent across platforms.
Many beginners expect the first user input to appear at index 0, but Python reserves sys.argv[0] for the script's filename. The actual arguments begin at sys.argv[1]. Understanding this behavior helps avoid indexing mistakes when accessing command line arguments in Python.
The simplest approach is to create a small script that prints sys.argv and execute it from a terminal with different values. Start with one argument, then try multiple inputs, quoted strings, and numbers. This hands-on practice makes using command line arguments in Python much easier to understand.
Yes. The argparse module lets you mix required positional arguments with optional flags in a single command. This approach keeps essential inputs mandatory while allowing users to customize program behavior with additional options, making command-line tools both flexible and user-friendly.
If you're accepting command line arguments in Python with sys.argv, you can loop through the list to process every value. When using argparse, the nargs parameter allows your script to accept one or more inputs under a single argument, which is cleaner for larger programs.
The --help flag automatically displays usage instructions, available options, and argument descriptions when your program uses argparse. It helps users understand how to run the script correctly without reading the source code, reducing mistakes and making your command-line interface easier to use.
Start by checking whether the required arguments are present before using them. For larger applications, argparse performs much of this validation automatically and provides clear error messages. This approach prevents crashes and improves the overall reliability of your Python scripts.
Absolutely. Automation is one of the most common reasons developers use command-line arguments. Instead of changing values inside the script, you simply pass different filenames, folders, dates, or configuration options each time the program runs, making repetitive tasks much easier to automate.
Most learners should begin with sys.argv because it clearly shows how Python receives arguments from the command line. Once you're comfortable with the basics, move to argparse to build applications that support optional arguments, validation, and built-in help documentation.
Developers use what are command line arguments in Python concepts to build file converters, backup utilities, deployment scripts, testing tools, data-processing pipelines, and system administration utilities. Since the same program can work with different inputs, command-line arguments make scripts reusable and much easier to integrate into automated workflows.
928 articles published
We are an online education platform providing industry-relevant programs for professionals, designed and delivered in collaboration with world-class faculty and businesses. Merging the latest technolo...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Top Resources