Arguments
argv¶
argv
stands for "argument vector." It’s a feature in Python that allows you to pass command-line arguments to your script when you run it. This is useful when you want your script to handle different inputs without changing the code itself.
How It Works¶
When you run a Python script from the command line, you can provide extra information after the script name. For example:
In this case, arg1
, arg2
, and arg3
are command-line arguments. argv
helps you capture and use these arguments in your script.
Using argv
in a Script¶
Here’s a simple example:
import sys
# Print all arguments
print("All arguments:", sys.argv)
# Access individual arguments
if len(sys.argv) > 1:
print("First argument:", sys.argv[1])
Explanation¶
sys.argv
is a list that contains all command-line arguments passed to the script.sys.argv[0]
is always the script name (myscript.py
in this case).sys.argv[1]
,sys.argv[2]
, etc., are the actual arguments you pass to the script.
Example¶
If you run:
The output will be:
Why It’s Useful¶
argv
is handy for creating scripts that need to handle different inputs or configurations without hardcoding values. For example, a script that processes files can use argv
to specify which file to process, making the script flexible and reusable.