A Comprehensive beginner friendly tutorial on using command-line arguments in Python
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.
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:
for arg in sys.argv:
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:
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
if len(sys.argv) > 1:
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 :
greet.py is the name of the Python file.