暗黑模式
In Python, you can use the sys.argv
list or the argparse
module to read and handle command-line arguments. Here's how you can do both:
1. Using sys.argv
The sys.argv
list contains all the command-line arguments passed to the script. The first element is the script name, and the following elements are the arguments.
Example:
python
import sys
# Access command-line arguments
print("Script name:", sys.argv[0]) # First argument is always the script name
if len(sys.argv) > 1:
print("Arguments:", sys.argv[1:]) # Remaining arguments
# Example usage: python script.py arg1 arg2
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
2. Using argparse
(Recommended)
The argparse
module provides a more powerful and user-friendly way to handle command-line arguments. You can define arguments, types, default values, and even display help messages.
Example:
python
import argparse
# Create argument parser
parser = argparse.ArgumentParser(description="A script to demonstrate command-line args.")
# Define arguments
parser.add_argument("arg1", type=int, help="First argument (an integer)")
parser.add_argument("arg2", type=str, help="Second argument (a string)")
parser.add_argument("--optional", type=float, default=1.0, help="An optional argument (default is 1.0)")
# Parse the arguments
args = parser.parse_args()
# Access the arguments
print("Arg1:", args.arg1)
print("Arg2:", args.arg2)
print("Optional argument:", args.optional)
# Example usage: python script.py 42 hello --optional 3.14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
When to Use Each:
- Use
sys.argv
for very simple scripts with minimal argument handling. - Use
argparse
for more robust scripts that require features like validation, default values, and help messages.
If you need further explanation or want help extending this script, feel free to ask! 😊