Concepts / Passing Arguments to Python Programs

Passing Arguments to Python Programs

The sys.argv variable is a list of strings (lists are explained in detail in a later chapter. Specifically, the sys.argv contains the list of command line arguments i.e. the arguments passed to your program using the command line.

  • 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.

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?

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

OS passes to PythonPython organizesProgram runsTerminal Commandpython script.py arg1 arg2Python Parses CommandSplits into tokenssys.argv CreatedList of strings builtAvailable in ProgramAccess via sys.argv[i]
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.

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?

Identify the command: The full command is: python greet.py Alice 25

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)

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

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])

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

Why sys.argv[0] Matters

Script name extractedFirst argumentSecond argumentCommand Typedpython script.py arg1 arg2sys.argv[0]script.pysys.argv[1]arg1sys.argv[2]arg2
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

  • Forgetting to import sys

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

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

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

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

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

  • Assuming arguments are numbers

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

    Fix: Convert with int() or float(): int(sys.argv[1]) + int(sys.argv[2])

  • Accessing an argument that wasn't provided

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

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

  • Not handling spaces in arguments correctly

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

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

Key Takeaways

  • 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