Command Line Arguments in Python
Command-line arguments in Python allow you to pass data to your Python script when executing it from the terminal or command prompt. This is helpful for customizing the behavior of your script without modifying the code. Command-line arguments are passed as a list of strings to the Python script, and they are typically used to configure the script’s behavior dynamically.
Understanding sys.argv
The sys.argv is a list in Python that contains the command-line arguments passed to the script. The first element sys.argv[0] is always the name of the script. Subsequent elements sys.argv[1:] contain the arguments passed by the user. Here's an example of how it works:
1. Using Command-Line Arguments
import sys
# Get the script name and command-line arguments
print("Script name:", sys.argv[0])
print("Command-line arguments:", sys.argv[1:])
Output:
Why Use Command-Line Arguments?
Command-line arguments provide flexibility for developers to customize scripts without modifying the code each time. For example:
- Specify input or output file paths dynamically.
- Set configuration options (e.g., verbose output or debug mode).
- Pass values to control how the program behaves.
2. Using Command-Line Arguments for File Handling
import sys
if len(sys.argv) != 3:
print("Usage: python script.py <input_file> <output_file>")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
with open(input_file, 'r') as f:
content = f.read()
with open(output_file, 'w') as f:
f.write(content)