
Chapter 5 Command line arguments
5.1 Learning objectives
Understand how to accept command line arguments in Python scripts
Learn how to access command line arguments using the
sys
moduleUnderstand how to handle command line arguments
5.2 Printing All Command Line Arguments
Let’s make our Python scripts interactive by accepting input from the command line. Create a new file called 02-arguments.py
and type:
```python
#!/usr/bin/env python3
import sys
print(sys.argv)
```
Save the file and make it executable:
Now run it directly with some arguments:
You’ll see output like
['./02-arguments.py', 'hello', 'world', '123']
The sys
module provide access to the system-specific parameter. The variable sys.argv
contains all command line arguments passed to your script, including the script name itself as the first element.
5.3 Understanding Lists
Lists in Python are ordered collections of items enclosed in square brackets, like [1, 2, 3]
or ["apple", "banana"]
. Lists can contain different types of data and are accessed by the position (index), starting from 0. For example, my_list[0]
gets the first item, my_list[1]
gets the second item, and so in.
5.4 Accessing Specific Arguments
Lets modify our script to print just the second command line argument:
Run it with:
./02-arguments.py hello
This prints:
Notice how
sys.argv[0]
is always the script name, so the first actual argument is at index 1Warning: If you don’t provide enough arguments, Python will crash with an “IndexError”. We’ll learn to handle this with
if
statements later
5.5 Arguments Are Strings
Command line arguments are always strings, even if they look like numbers.
Update
02-arguments.py
Run it with:
./02-arguments.py 5 3
Output:
Without conversion, Python concatenates the strings “5” and “3” into “53”. The int()
function converts string representations of numbers into actual integers that can be used in mathematical operations.