Python Command Line Arguments
Introduction to Command-Line Arguments
Giving Your Program Instructions
So far, our programs have been self-contained. To change what they do, we've had to edit the code itself. But what if you want to give a program input when you run it? That's where command-line arguments come in.
Think of running a program like ordering a pizza. The program is the pizza place, and the arguments are your toppings. Instead of the pizza place deciding your toppings for you (hard-coding them), you tell them what you want when you order. This makes the program flexible and reusable.
Command-line arguments are pieces of information you provide to a program when you execute it from the terminal.
Python has a built-in module called sys that lets us access these arguments. The arguments are stored in a list called argv, which stands for "argument vector."
To use it, you first need to import the sys module at the top of your script.
import sys
# sys.argv is a list containing all command-line arguments.
print(sys.argv)
Let's save that code as show_args.py. If you run it from your terminal like this:
python show_args.py
The output will be a list with one item:
['show_args.py']
This shows an important rule: the very first item in the sys.argv list, at index 0, is always the name of the Python script itself.
Using the Arguments
The real power comes from the arguments that follow the script name. Each word you type after the script name is added to the sys.argv list as a separate string.
Let's try running our script again, but with a few arguments.
python show_args.py hello world 123
This time, the output will be:
['show_args.py', 'hello', 'world', '123']
As you can see, sys.argv[0] is the script name, sys.argv[1] is 'hello', sys.argv[2] is 'world', and so on. We can use these list elements in our program.
Here’s a simple program named greeter.py that greets a person by name.
import sys
# The first argument is the name we want to greet
name = sys.argv[1]
print(f"Hello, {name}!")
If you run this program and provide your name as an argument:
python greeter.py Alice
The program will greet Alice personally.
Hello, Alice!
Working with Arguments
One crucial thing to remember is that every argument in sys.argv is a string, even if it looks like a number. If you want to perform mathematical operations, you must first convert the string arguments into numbers using int() or float().
Let's create a program called add.py that takes two numbers from the command line and adds them together.
import sys
# Get the first number (at index 1)
num1_str = sys.argv[1]
# Get the second number (at index 2)
num2_str = sys.argv[2]
# Convert strings to integers
num1 = int(num1_str)
num2 = int(num2_str)
# Calculate and print the sum
result = num1 + num2
print(f"The sum is: {result}")
Now, run it from the terminal with two numbers.
python add.py 7 5
The output will be exactly what you expect.
The sum is: 12
What would happen if you didn't convert the strings to integers? Python would perform string concatenation, joining '7' and '5' to make '75', which isn't what we want for a calculator.
This is just the beginning. You can now write programs that are far more interactive and powerful by accepting input directly from the command line.
What is the primary purpose of using command-line arguments?
If you run the script calculate.py with the command python calculate.py 10 5, what will be the value and type of sys.argv[1] inside the script?