Member-only story
The Ultimate Guide to Command Line Arguments in Python Scripts
A Comprehensive beginner friendly tutorial on using command-line arguments in Python
Introduction
Command line arguments are a powerful way to pass parameters to a program when it is executed. They allow users to customize the behavior of the program without modifying its source code. Command-line arguments are used extensively in the Unix/Linux command-line interface and are also commonly used in scripting languages like Python.
Compared to other types of user input like prompts and web forms, command-line arguments are more efficient and can be automated easily. They can also be used to run scripts in batch mode, without the need for user interaction.
Basic Syntax
In Python, command-line arguments are accessed through the sys.argv
list. The first item in the list is always the name of the script itself, and subsequent items are the arguments passed to the script.
Here is an example script that prints out the command line arguments:
import sys
for arg in sys.argv:
print(arg)
If you save this script as test.py
, you can run it from the command line with arguments like this:
python test.py arg1 arg2 arg3
This will return the output:
test.py
arg1
arg2
arg3
As you can see, the sys.argv
list contains all the arguments passed to the script, including the script name itself.
You can access individual arguments by indexing the sys.argv
list:
import sys
if len(sys.argv) > 1:
print(f"Hello, {sys.argv[1]}!")
else:
print("Hello, world!")
This script takes a single argument and prints out a customized greeting. If no argument is provided, it defaults to “Hello, world!”. Here is an example of usage:
python greet.py Alice
This will print the output :
Hello, Alice!
greet.py
is the name of the Python file.