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
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:
python script.py arg1 arg2 arg3Output:
Script name: script.py
Arguments passed:
arg1
arg2
arg32. Accessing Specific Command-Line Arguments
Example Usage:
Output:
3. Using Command-Line Arguments for Calculations
Example Usage:
Output:
4. Handling Optional Arguments
Example Usage:
Output:
If no argument is provided:
Output:
5. Argument Parsing with sys.argv for a Simple Command-Line Tool
Example Usage:
Output:
6. Handling Invalid Arguments
Example Usage:
Output:
If an invalid argument is passed:
Output:
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