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.
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].
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
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?
- 1Identify the command
The full command is: python
greet.pyAlice 25 - 2Map 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) - 3Access the name
To get the name, use
sys.argv[1], which gives you 'Alice' - 4Access 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 withint(sys.argv[2])
name = sys.argv[1] gives 'Alice', and age = sys.argv[2] gives '25' as a string
Why sys.argv[0] Matters
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 likeWriting sys.argv[1] without import sys at the top of the file
Why it failsPython won't recognize the name sys and will raise a
NameErrorDo this insteadAlways 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 likeRunning python script.py hello and expecting sys.argv[0] to be 'hello'
Why it failssys.argv[0] is always the script name ('script.py'), so the first user argument is actuallysys.argv[1]Do this insteadRemember the offset: user arguments start at index 1, not 0
Common mistake Assuming arguments are numbers
What it looks likeRunning python script.py 10 20 and then trying sys.argv[1] + sys.argv[2] expecting 30
Why it failssys.argvcontains strings, so '10' + '20' results in the string '1020', not the number 30Do this insteadConvert with int() or float(): int(sys.argv[1]) + int(sys.argv[2])Common mistake Accessing an argument that wasn't provided
What it looks likeRunning python script.py arg1 but then trying to access sys.argv[2]
Why it failssys.argv[2] doesn't exist, so Python raises anIndexErrorDo this insteadCheck 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 likeRunning python script.py hello world and expecting one argument 'hello world'
Why it failsThe terminal splits on spaces, so this creates two separate arguments: 'hello' and 'world'
Do this insteadIf 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
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 atsys.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.argvis 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 atsys.argv[1] - 3To use
sys.argv, you must import the sys module at the top of your program - 4All items in
sys.argvare strings, even if they look like numbers—convert them withint()orfloat()if needed - 5Most 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.argvis a list of strings containing the script name and all command-line arguments passed to your programsys.argv[0] holds the script name; the first user argument is atsys.argv[1], the second atsys.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.argvor use error handling to avoidIndexErrorwhen accessing arguments that may not have been provided - Test programs that use
sys.argvfrom the terminal to ensure they work correctly with real command-line input