Exam2022 Flashcards
1
Q
A
2
Q
A
3
Q
A
4
Q
A
python script.py input.txt output.txt –verbose
The argparse module in Python provides a way to handle command-line arguments passed to a script. It allows you to define what arguments your program requires, parse those arguments, and automatically generate help and usage messages.
Here’s an example of how to use argparse:
import argparse Create the parser parser = argparse.ArgumentParser(description="Example script using argparse") Add arguments parser.add_argument('input', type=str, help='Input file path') parser.add_argument('output', type=str, help='Output file path') parser.add_argument('--verbose', action='store_true', help='Increase output verbosity') Parse the arguments args = parser.parse_args() Use the arguments print(f"Input file: {args.input}") print(f"Output file: {args.output}") if args.verbose: print("Verbose mode is on") Example usage # python script.py input.txt output.txt --verbose
Explanation:
- Create the parser: argparse.ArgumentParser is used to create a new argument parser object.
- Add arguments: add_argument is used to specify which command-line options the program is expecting. In this example, input and output are positional arguments, and –verbose is an optional argument.
- Parse the arguments: parse_args parses the command-line arguments and returns them as an object with attributes.
- Use the arguments: The parsed arguments can be accessed as attributes of the args object.
When you run the script with the command:
python script.py input.txt output.txt --verbose
The output will be:
Input file: input.txt Output file: output.txt Verbose mode is on
5
Q
A
6
Q
A
7
Q
A
8
Q
A
9
Q
A
10
Q
A
11
Q
A
12
Q
A
13
Q
A
14
Q
A
15
Q
A