How to Use Command Line Arguments in Python
Command line arguments let you pass values to a Python script when you run it in a terminal.
This is useful when you want the same script to work with different inputs, such as:
- a file name
- a number
- a short text value
- a simple command
In this guide, you will learn how to pass arguments to a script, read them with sys.argv, and handle missing input safely.
Quick example #
import sys
print(sys.argv)
if len(sys.argv) > 1:
print("First argument:", sys.argv[1])
else:
print("No argument was provided.")
sys.argv is a list. Item 0 is the script name. Real user arguments start at index 1.
What command line arguments are #
Command line arguments are values you type after the script name when running Python in the terminal.
For example:
python script.py hello 123
In this command:
script.pyis the Python filehellois the first argument123is the second argument
Command line arguments help one script behave differently based on the values you pass in.
They are often used for:
- file names
- numbers
- options
- simple commands
This page focuses on basic positional arguments with sys.argv, not full argument parsers.
How to run a script with arguments #
A common pattern looks like this:
python script.py hello 123
On some systems, you may need:
python3 script.py hello 123
Python receives each space-separated value as a string.
So this command:
python script.py apple banana
passes two arguments:
"apple""banana"
If one argument contains spaces, put it in quotes:
python script.py "hello world"
Without quotes, the terminal treats each word as a separate argument.
If you are new to running scripts from the terminal, see how to run Python code from the command line and IDEs.
Read arguments with sys.argv #
To use command line arguments, first import the sys module:
import sys
Then use sys.argv.
sys.argv is a list of strings:
sys.argv[0]is the script name or pathsys.argv[1]is the first real argumentsys.argv[2]is the second real argument
Here is a simple example:
import sys
print(sys.argv)
If you run:
python script.py hello 123
the output will look similar to this:
['script.py', 'hello', '123']
A very important rule: check len(sys.argv) before using an index like sys.argv[1].
That helps you avoid an error if no argument was passed. If you want a deeper explanation, see sys.argv explained.
Simple working example #
This example prints all arguments and then reads the first one safely.
import sys
print("All arguments:", sys.argv)
if len(sys.argv) > 1:
print("First argument:", sys.argv[1])
else:
print("No argument was provided.")
Run it without arguments #
Command:
python script.py
Possible output:
All arguments: ['script.py']
No argument was provided.
Run it with one argument #
Command:
python script.py hello
Possible output:
All arguments: ['script.py', 'hello']
First argument: hello
This is a good beginner pattern because it shows exactly what Python receives.
Convert argument types when needed #
Arguments from sys.argv always arrive as strings.
That means this:
import sys
print(type(sys.argv[1]))
prints:
<class 'str'>
If you need numbers, convert them.
Convert to int #
Use int() for whole numbers:
import sys
if len(sys.argv) > 1:
number = int(sys.argv[1])
print(number + 5)
else:
print("Please provide a number.")
Example command:
python script.py 10
Output:
15
Convert to float #
Use float() for decimal numbers:
import sys
if len(sys.argv) > 1:
number = float(sys.argv[1])
print(number * 2)
else:
print("Please provide a number.")
If needed, you can learn more about int() and float().
Handle invalid input safely #
If the value is not a valid number, conversion fails.
import sys
if len(sys.argv) > 1:
try:
number = int(sys.argv[1])
print("Number:", number)
except ValueError:
print("The argument must be a whole number.")
else:
print("Please provide a number.")
Example:
python script.py hello
Output:
The argument must be a whole number.
Work with multiple arguments #
You can read more than one argument by position.
Example: read a name and an age.
import sys
if len(sys.argv) >= 3:
name = sys.argv[1]
age = int(sys.argv[2])
print("Name:", name)
print("Age:", age)
else:
print("Usage: python script.py <name> <age>")
Command:
python script.py Maya 14
Output:
Name: Maya
Age: 14
For positional arguments, order matters.
In this example:
- the first argument must be the name
- the second argument must be the age
If the user swaps them, the script may fail or produce the wrong result.
Handle missing arguments safely #
A common beginner mistake is writing code like this:
import sys
print(sys.argv[1])
This works only if the user passed at least one argument.
If not, Python raises an error because index 1 does not exist.
A safer version checks the list length first:
import sys
if len(sys.argv) < 2:
print("Usage: python script.py <value>")
sys.exit()
print("You entered:", sys.argv[1])
This does three useful things:
- checks whether input is missing
- prints a short usage message
- exits early if required input was not provided
If you want to learn more about stopping a script early, see sys.exit() explained.
If you see an out-of-range error, read how to fix IndexError: list index out of range.
When to use argparse instead #
Use sys.argv when your script is simple and you only need a few positional arguments.
For example, sys.argv is fine for:
- small practice scripts
- simple command-line tools
- learning how terminal input works
Use argparse when your script needs features like:
- named options such as
--file - optional flags such as
--verbose - built-in help messages
- more structured input checking
A good next step is to start with sys.argv, then move to argparse as your tools get bigger.
Common mistakes #
Here are some common problems beginners run into:
- Using
sys.argv[1]when no argument was passed - Forgetting to
import sys - Expecting numbers but getting strings
- Forgetting quotes around arguments with spaces
- Assuming
sys.argv[0]is the first user value
You can test your script with commands like these:
python script.py
python script.py hello
python script.py 10 20
python script.py "hello world"
python3 script.py test
FAQ #
What is sys.argv[0] in Python? #
It is the script name or script path, not the first user argument.
Are command line arguments strings in Python? #
Yes. Values in sys.argv are strings, so convert them if you need numbers.
How do I pass text with spaces? #
Wrap the argument in quotes in the terminal, such as "my file.txt".
How do I avoid IndexError with sys.argv? #
Check len(sys.argv) before reading a specific index like sys.argv[1].
Should I use sys.argv or argparse? #
Use sys.argv for simple scripts. Use argparse for larger tools with named options and help messages.
See also #
- Python sys module overview
- sys.argv explained
- sys.exit() explained
- How to run Python code from the command line and IDEs
- How to fix
IndexError: list index out of range - How to get user input in Python
Once you are comfortable with sys.argv, you can start building small command-line tools. After that, argparse is the natural next step for more advanced scripts.