132. Python's sys.argv
sys.argv is a list in Python, which contains the command-line arguments passed to a Python script. The first element, sys.argv[0], is the script name, and the subsequent elements (sys.argv[1:]) are the arguments provided by the user.
Here are some examples demonstrating how to use sys.argv to read command-line arguments in Python scripts:
1. Basic Example: Reading Command-Line Arguments
Copy
import sys
# Print the script name
print(f"Script name: {sys.argv[0]}")
# Print the command-line arguments passed to the script
print("Arguments passed:")
for arg in sys.argv[1:]:
print(arg)Example Usage:
Copy
python script.py arg1 arg2 arg3Output:
Copy
Script name: script.py
Arguments passed:
arg1
arg2
arg32. Accessing Specific Command-Line Arguments
Copy
Example Usage:
Copy
Output:
Copy
3. Using Command-Line Arguments for Calculations
Copy
Example Usage:
Copy
Output:
Copy
4. Handling Optional Arguments
Copy
Example Usage:
Copy
Output:
Copy
If no argument is provided:
Copy
Output:
Copy
5. Argument Parsing with sys.argv for a Simple Command-Line Tool
Copy
Example Usage:
Copy
Output:
Copy
6. Handling Invalid Arguments
Copy
Example Usage:
Copy
Output:
Copy
If an invalid argument is passed:
Copy
Output:
Copy
Key Points:
sys.argvprovides access to the command-line arguments passed to a script.Indexing:
sys.argv[0]is always the script name, andsys.argv[1:]contains the actual arguments.Error Handling: Ensure that the correct number of arguments is passed, and handle invalid inputs gracefully.
Last updated