Concepts / Passing Arguments to Python Programs

Passing Arguments to Python Programs

To use sys.argv in your program, you must first import the sys module at the top of your script with import sys. Without this import, Python won't know what sys.argv is.

  • Programming

What Are Command-Line Arguments?

When you run a Python program from the terminal, you can pass extra information to it right on the command line. For example, instead of just typing python script.py, you might type python script.py arg1 arg2 arg3. Those extra pieces of text—arg1, arg2, arg3—are command-line arguments. They're a way to tell your program what to do without hard-coding values inside the script itself. Python automatically collects all these arguments and stores them in a special variable called sys.argv so your program can use them.

In the real world

Imagine a backup program that copies files. Instead of editing the script every time you want to back up a different folder, you could run python backup.py /home/user/documents /backup/location. The program receives the source and destination paths as arguments, making it flexible and reusable.

Understanding sys.argv

sys.argv is a list of strings. A list is an ordered collection of items, and each item in sys.argv is a string—a piece of text. When you run a Python program from the command line, Python automatically creates sys.argv and fills it with the arguments you passed. The crucial detail: sys.argv[0] is always the name of the script itself, and the actual arguments you passed start at sys.argv[1].

sys.argv[0]script.pysys.argv[1]arg1sys.argv[2]arg2sys.argv[3]arg3
When you run a command with arguments, sys.argv becomes a list where each position holds a specific piece of information. Which index holds the script name, and which holds your actual arguments?
Key point

To use sys.argv in your program, you must first import the sys module at the top of your script with import sys. Without this import, Python won't know what sys.argv is.

How Arguments Flow from Terminal to Your Program

Terminal Commandpython script.py arg1 arg2Python Parses CommandSplits into tokenssys.argv CreatedList of strings builtAvailable in ProgramAccess via sys.argv[i]OS passes to PythonPython organizesProgram runs
What's the path from typing a command in the terminal to sys.argv being populated inside my Python program?

When you type a command in the terminal and press Enter, the operating system passes that entire command to Python. Python then splits the command into separate pieces: the word python, the script name, and each argument. It stores all of these as strings in the sys.argv list. Your program can then access any of these pieces by index.

Accessing Arguments by Index

To get a specific argument, you use the index notation sys.argv[i], where i is a number starting from 0. Remember: sys.argv[0] is the script name, so the first actual argument you passed is at sys.argv[1], the second is at sys.argv[2], and so on. If you try to access an index that doesn't exist—for example, sys.argv[5] when you only passed two arguments—Python will raise an IndexError.

Worked example

Accessing Arguments from a Command

You run the command: python greet.py Alice 25. Your program needs to extract the name and age. What index does each value occupy in sys.argv?

  1. 1
    Identify the command

    The full command is: python greet.py Alice 25

  2. 2
    Map each piece to sys.argv

    sys.argv[0] = 'greet.py' (the script name), sys.argv[1] = 'Alice' (first argument), sys.argv[2] = '25' (second argument)

  3. 3
    Access the name

    To get the name, use sys.argv[1], which gives you 'Alice'

  4. 4
    Access the age

    To get the age, use sys.argv[2], which gives you '25'. Note: this is a string, not a number, so if you need to do math, convert it with int(sys.argv[2])

Result

name = sys.argv[1] gives 'Alice', and age = sys.argv[2] gives '25' as a string

Why sys.argv[0] Matters

Command Typedpython script.py arg1 arg2sys.argv[0]script.pysys.argv[1]arg1sys.argv[2]arg2Script name extractedFirst argumentSecond argument
Why is the program name itself stored in sys.argv, and how does that differ from the actual arguments I pass?

The script name is included in sys.argv[0] because it's useful metadata. Your program can know its own name, which is handy for error messages, logging, or when the same script is run under different names. However, when you're thinking about the arguments the user passed to your program, you should start counting from sys.argv[1], not sys.argv[0].

Common Mistakes with sys.argv

  • Common mistake

    Forgetting to import sys

    What it looks like

    Writing sys.argv[1] without import sys at the top of the file

    Why it fails

    Python won't recognize the name sys and will raise a NameError

    Do this instead

    Always add import sys as the first line of your program if you plan to use sys.argv

  • Common mistake

    Treating sys.argv[0] as the first user argument

    What it looks like

    Running python script.py hello and expecting sys.argv[0] to be 'hello'

    Why it fails

    sys.argv[0] is always the script name ('script.py'), so the first user argument is actually sys.argv[1]

    Do this instead

    Remember the offset: user arguments start at index 1, not 0

  • Common mistake

    Assuming arguments are numbers

    What it looks like

    Running python script.py 10 20 and then trying sys.argv[1] + sys.argv[2] expecting 30

    Why it fails

    sys.argv contains strings, so '10' + '20' results in the string '1020', not the number 30

    Do this instead
    Convert with int() or float(): int(sys.argv[1]) + int(sys.argv[2])
  • Common mistake

    Accessing an argument that wasn't provided

    What it looks like

    Running python script.py arg1 but then trying to access sys.argv[2]

    Why it fails

    sys.argv[2] doesn't exist, so Python raises an IndexError

    Do this instead

    Check the length of sys.argv first, or use a try-except block to handle missing arguments gracefully

  • Common mistake

    Not handling spaces in arguments correctly

    What it looks like

    Running python script.py hello world and expecting one argument 'hello world'

    Why it fails

    The terminal splits on spaces, so this creates two separate arguments: 'hello' and 'world'

    Do this instead

    If you need to pass text with spaces, wrap it in quotes: python script.py 'hello world'

Using sys.argv in an IDE

If you're using an IDE (like PyCharm, VS Code, or IDLE) to write and run your programs, you may not have a traditional terminal where you type commands. Most IDEs provide a way to specify command-line arguments in their menus or configuration settings. Look for options like 'Run Configuration', 'Program Arguments', or 'Command Line Arguments' in your IDE's settings. This allows you to test your program with different arguments without leaving the IDE.

Practice: Extracting and Using Arguments

EASY

Write a Python program that accepts two arguments from the command line: a first name and a last name. The program should print a greeting that says 'Hello, [first name] [last name]!'. Test your program by running it with different names. What happens if you run it with only one argument? What happens if you run it with three arguments?

Hints
  • Remember to import sys at the top
  • The first argument is at sys.argv[1], the second at sys.argv[2]
  • You can concatenate strings with the + operator
  • To test what happens with missing arguments, you could add a check like if len(sys.argv) < 3: print('Not enough arguments')

Summary

  1. 1
    sys.argv is a list of strings that stores command-line arguments passed to your Python program
  2. 2
    sys.argv[0] always contains the script name; actual user arguments start at sys.argv[1]
  3. 3
    To use sys.argv, you must import the sys module at the top of your program
  4. 4
    All items in sys.argv are strings, even if they look like numbers—convert them with int() or float() if needed
  5. 5
    Most IDEs provide a way to specify command-line arguments in their settings, but testing from a real terminal is more reliable

At a glance

  • sys.argv is a list of strings containing the script name and all command-line arguments passed to your program
  • sys.argv[0] holds the script name; the first user argument is at sys.argv[1], the second at sys.argv[2], and so on
  • Always import sys before using sys.argv, and remember that all arguments are strings—convert them to numbers if your program needs arithmetic
  • Check the length of sys.argv or use error handling to avoid IndexError when accessing arguments that may not have been provided
  • Test programs that use sys.argv from the terminal to ensure they work correctly with real command-line input

Related concepts

More concepts starting with P