sys.argv Explained
sys.argv lets a Python script read values passed from the command line.
It is useful for small scripts where you want to give input when you run the file, such as a file name, a word, or a number.
Quick example #
import sys
print(sys.argv)
# Run from terminal:
# python script.py hello 123
sys.argv is a list of command line arguments. The first item is the script name.
What sys.argv is #
sys.argv comes from Python’s sys module. If you want to use it, you must first import sys.
Key points:
sys.argvstores command line arguments in a list- Arguments are values typed after the script name
sys.argv[0]is usually the script file name- Every item in
sys.argvis a string
For example, if you run:
python script.py hello 123
Python will usually build this list:
['script.py', 'hello', '123']
That means:
sys.argv[0]is'script.py'sys.argv[1]is'hello'sys.argv[2]is'123'
If you want a broader introduction, see the Python sys module overview.
When to use sys.argv #
Use sys.argv when:
- You want input from the command line
- You are building a small script or beginner command line tool
- You want to pass file names, numbers, or simple options
It is a good fit for simple tasks such as:
- adding two numbers
- reading a file name
- printing a custom message
It is not ideal for more advanced command line programs with many options. For that, argparse is usually a better choice.
Basic example #
Here is a simple script that prints the full sys.argv list.
import sys
print("Full argument list:")
print(sys.argv)
If the file is named script.py and you run:
python script.py apple banana
You might see:
Full argument list:
['script.py', 'apple', 'banana']
The script name appears first because Python includes it as the first item in the argument list.
Reading specific arguments #
You can access individual values by index.
import sys
print("Script name:", sys.argv[0])
if len(sys.argv) > 1:
print("First user argument:", sys.argv[1])
if len(sys.argv) > 2:
print("Second user argument:", sys.argv[2])
Important points:
- User-provided values start at
sys.argv[1] sys.argv[0]is usually the script name- Always check the length first with
len()
Why this matters:
If you try to read sys.argv[1] when no argument was given, Python raises an error because that list position does not exist. This is the same kind of problem explained in IndexError: list index out of range.
Example of unsafe code:
import sys
print(sys.argv[1])
If you run:
python script.py
You will get an IndexError.
Safer version:
import sys
if len(sys.argv) > 1:
print(sys.argv[1])
else:
print("No argument was provided.")
Converting argument types #
All command line arguments are strings by default.
That means this code does not add numbers correctly:
import sys
a = sys.argv[1]
b = sys.argv[2]
print(a + b)
If you run:
python script.py 5 10
The result is:
510
This happens because Python is joining two strings, not adding two numbers.
To work with numbers, convert them first.
Convert to int #
import sys
if len(sys.argv) > 2:
a = int(sys.argv[1])
b = int(sys.argv[2])
print(a + b)
else:
print("Please provide two whole numbers.")
Output for:
python script.py 5 10
is:
15
You can learn more about integer conversion in Python int() explained.
Convert to float #
import sys
if len(sys.argv) > 2:
a = float(sys.argv[1])
b = float(sys.argv[2])
print(a + b)
else:
print("Please provide two decimal numbers.")
This is useful when values may include decimals such as 2.5 and 4.1.
Invalid conversions #
If a value cannot be turned into a number, Python raises ValueError.
Example:
import sys
number = int(sys.argv[1])
print(number)
Run:
python script.py hello
This fails because "hello" is not a valid integer.
Common beginner errors #
Here are some common problems when using sys.argv:
- Forgetting to
import sys - Using
sys.argv[1]when no argument was passed - Trying to add argument values as numbers without converting them
- Running code inside an IDE without setting command line arguments first
Common error causes include:
IndexErrorwhen accessing a missing argumentValueErrorwhen converting text withint()orfloat()TypeErroror incorrect results when treating strings like numbers- Confusion from counting the script name as a user argument
If you are just getting started with this topic, the step-by-step guide on how to use command line arguments in Python may help.
Simple pattern for safer scripts #
A small script should check input before using it.
Here is a safe pattern:
import sys
if len(sys.argv) != 3:
print("Usage: python script.py <num1> <num2>")
sys.exit()
try:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
except ValueError:
print("Both arguments must be whole numbers.")
sys.exit()
print("Sum:", num1 + num2)
What this script does:
- checks that exactly two user arguments were given
- prints a usage message if they are missing
- converts the values inside
try/except - exits early if the input is invalid
If you want to stop a script early, see sys.exit() explained.
When to use argparse instead #
sys.argv is great for learning and for very small scripts.
Use argparse instead when:
- you want named options like
--fileor--verbose - you want automatic help messages
- your script has many arguments
- your command line tool is getting larger
A good learning path is:
- Start with
sys.argv - Build one or two small scripts
- Move to
argparsewhen you need more structure
For a next step, see the Python argparse example.
FAQ #
What is sys.argv[0]? #
It is usually the script name or path used to run the script.
Why are command line arguments strings? #
Python reads terminal input as text, so you must convert values yourself when needed.
What happens if I use sys.argv[1] with no argument? #
Python raises IndexError because that list position does not exist.
Can I use sys.argv in an IDE? #
Yes, but many IDEs require you to set command line arguments in the run configuration.
Should I learn sys.argv or argparse first? #
Start with sys.argv because it is simpler, then move to argparse for more advanced scripts.