Command Line Arguments in Python: sys.argv, argparse Guide

By upGrad

Updated on Jul 23, 2026 | 6 min read | 1.43K+ views

Share:

Key Takeaway  

  • Command Line Arguments are values passed to a Python script from the command line when the script starts running. 
  • Instead of hardcoding values or waiting for a prompt, you type them right into the terminal.

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.

What Are Command Line Arguments in Python?

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:

  • Running automation scripts with different file names each time
  • Passing a date range into a report generator
  • Feeding a model file into a data processing script
  • Setting flags for debug mode or verbose logging in CI/CD pipelines

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.

When Should You Use Command Line Arguments?

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. 

Read: Python’s most popular machine learning libraries

Python Command Line Arguments Example

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

360° Career Support

Executive Diploma12 Months
background

O.P.Jindal Global University

MBA from O.P.Jindal Global University

Live Case Studies and Projects

Master's Degree12 Months

How to Use Command Line Arguments in Python

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.

Basic Syntax

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.

Accessing Command Line Arguments Using sys.argv

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.

What is sys.argv in Python

sys.argv is just a list of strings. Nothing more.

  • sys.argv[0] is the script name, always
  • sys.argv[1] is your first real argument
  • Every value inside is a string, even if you typed a number

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.

Example: Reading User Input from the Command Line

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

Common Errors With sys.argv

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

Using argparse in Python for Command Line Arguments

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.

Creating Your First Argument Parser

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 vs Optional Arguments

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

Python Optional Command Line Arguments

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.

Required Arguments and Defaults

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

Python Command Line Arguments Multiple Values and Type Conversion

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. 

Automatically Generated Help Messages

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

sys.argv vs argparse in Python

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

Handling Multiple Values and Arguments With Spaces

Two situations catch beginners off guard almost every time. Let's cover both.

Python Command Line Arguments with Spaces  

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

Passing Multiple Values

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

Python argparse Unrecognized Arguments Error

This error shows up constantly, and it's almost always one of three things.

  • A typo in the flag name, like --verbos instead of --verbose
  • An extra value your parser wasn't set up to accept
  • A positional argument passed in the wrong order

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

Best Practices for Command Line Arguments in Python

A few habits separate messy scripts from ones people can actually reuse.

  • Prefer argparse once your script takes more than one or two inputs
  • Validate values instead of trusting they're always correct
  • Write descriptive help text for every argument you define
  • Keep argument names consistent across related scripts
  • Test your commands before pushing them into a scheduled job or pipeline
  • Avoid hardcoding values that could just as easily be passed in

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.

Conclusion

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.

Frequently Asked Questions

1. Can I use command line arguments in Python without the sys module?

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. 

2. How do I run a Python script with command line arguments in Windows or macOS?

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. 

3. Why is sys.argv[0] the script name instead of the first argument?

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.

4. What's the easiest way to test command line arguments while learning 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.

5. Can I combine positional and optional arguments in the same Python script?

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. 

6. How do I accept a variable number of command line arguments in Python?

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. 

7. Why should I use the --help option in Python command-line 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. 

8. How do I safely handle missing or invalid command line arguments?

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.

9. Can I use command line arguments in Python automation 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.

10. Should beginners learn sys.argv or argparse first?

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. 

11. What are some real-world applications of command line arguments in Python?

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. 

upGrad

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

+91

By submitting, I accept the T&C and
Privacy Policy

Top Resources

Recommended Programs

upGrad

upGrad

Management Essentials

Case Based Learning

Certification

3 Months

IIMK
bestseller

Certification

6 Months

OPJ Logo
new course

Master's Degree

12 Months