Command-Line Flag Parsing for Output File Selection
๐ท๏ธ Final Capstone Engineer Script project / Project: System Health Reporter
๐งญ Context Introduction
When building a system health reporter, you often need to save results to a file for later review or sharing. Rather than hardcoding a filename, you can let users specify their own output file at runtime using command-line flags. This makes your script flexible, reusable, and professional. In this section, you'll learn how to parse a command-line flag that lets users choose where to save their report.
โ๏ธ Why Use Command-Line Flags for Output Files?
- Flexibility: Users can save reports to different locations without editing the script.
- Automation: Other scripts or cron jobs can pass filenames dynamically.
- Clarity: The script's behavior is explicit and easy to understand.
- Reusability: One script works for multiple scenarios (daily reports, backups, etc.).
๐ ๏ธ How Flag Parsing Works
- Python's built-in argparse module handles command-line flag parsing.
- You define expected flags (like --output or -o) and their types.
- When the script runs, it reads the flags and stores the values in variables.
- If a required flag is missing, argparse automatically shows a helpful error message.
๐ Basic Structure for Output File Selection
Here is the typical flow for adding an output file flag:
- Import the argparse module at the top of your script.
- Create an ArgumentParser object with a description of your tool.
- Add an argument using add_argument() with the flag name (e.g., --output).
- Specify a short alias (e.g., -o) for convenience.
- Set the argument as a string type (the default).
- Parse the arguments with parse_args().
- Use the parsed value as your output filename.
๐งช Example Script Flow
Consider a simple system health reporter that collects CPU and memory usage:
- The script defines a flag called --output with alias -o.
- The user runs the script like this: python health_reporter.py --output report.txt
- Inside the script, the value report.txt is stored in args.output.
- The script then opens that file and writes the health data to it.
- If the user runs the script without the flag, argparse shows a friendly error reminding them to provide a filename.
๐งฉ Comparison: Hardcoded vs. Flag-Based Output
| Feature | Hardcoded Filename | Flag-Based Output |
|---|---|---|
| Flexibility | Low โ filename never changes | High โ user chooses each time |
| Automation | Requires manual edits | Works with cron and scripts |
| Error Handling | None built-in | Automatic missing flag messages |
| User Experience | Confusing for others | Clear and professional |
| Code Reusability | One-time use | Reusable across projects |
๐ต๏ธ Common Pitfalls to Avoid
- Forgetting to parse arguments: Always call parse_args() after defining all flags.
- Using the wrong variable name: The attribute name matches the flag name (e.g., --output becomes args.output).
- Not handling missing flags gracefully: Use required=True in add_argument() to enforce the flag.
- Overwriting existing files without warning: Consider adding a confirmation prompt or a --force flag.
- Mixing flag order: argparse handles any order, but keep your flags consistent for readability.
๐ง Key Takeaways
- Command-line flags make your scripts flexible and user-friendly.
- Python's argparse module handles all the heavy lifting for flag parsing.
- Always use descriptive flag names like --output for clarity.
- Test your script with and without flags to ensure proper error handling.
- A well-designed flag system makes your tool ready for automation and production use.
๐ Next Steps
- Practice adding an --output flag to a simple script that writes system information.
- Experiment with optional flags (e.g., --verbose or --format).
- Combine multiple flags to create a fully configurable health reporter.
- Test your script with different filenames and paths to confirm it works correctly.
This technique allows engineers to specify an output file path from the command line when running their Python script.
๐งช Example 1: Basic flag with sys.argv
This example shows how to read a command-line argument as a filename using the raw sys.argv list.
import sys
# Get the filename from command-line argument
filename = sys.argv[1]
print(f"Output will be saved to: {filename}")
๐ค Output: Output will be saved to: report.txt (when run as python script.py report.txt)
๐งช Example 2: Using argparse for a named flag
This example introduces the argparse module to define a --output flag.
import argparse
# Create the argument parser
parser = argparse.ArgumentParser()
# Add the --output flag
parser.add_argument("--output", help="Path to output file")
# Parse the arguments
args = parser.parse_args()
# Use the provided filename
output_file = args.output
print(f"Output file: {output_file}")
๐ค Output: Output file: results.txt (when run as python script.py --output results.txt)
๐งช Example 3: Default filename when no flag is given
This example shows how to set a default output filename when the user does not provide the flag.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--output", default="system_report.txt", help="Output file path")
args = parser.parse_args()
output_file = args.output
print(f"Output file: {output_file}")
๐ค Output: Output file: system_report.txt (when run as python script.py)
๐งช Example 4: Writing system health data to the chosen file
This example demonstrates writing actual content to the file specified by the --output flag.
import argparse
import datetime
parser = argparse.ArgumentParser()
parser.add_argument("--output", default="health_report.txt", help="Output file path")
args = parser.parse_args()
# Generate a simple health report
timestamp = datetime.datetime.now()
report_line = f"System health check at {timestamp}: All services running\n"
# Write to the chosen file
with open(args.output, "w") as f:
f.write(report_line)
print(f"Report written to: {args.output}")
๐ค Output: Report written to: health_report.txt (when run as python script.py --output health_report.txt)
๐งช Example 5: Combining multiple flags with output file selection
This example shows a more practical scenario where the engineer selects both output format and output file.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--output", default="report.txt", help="Output file path")
parser.add_argument("--format", choices=["text", "csv"], default="text", help="Output format")
args = parser.parse_args()
# Build content based on format choice
if args.format == "text":
content = "CPU: 45%\nMemory: 60%\nDisk: 80%"
elif args.format == "csv":
content = "metric,value\nCPU,45\nMemory,60\nDisk,80"
# Write to the chosen file
with open(args.output, "w") as f:
f.write(content)
print(f"Written {args.format} report to: {args.output}")
๐ค Output: Written csv report to: report.csv (when run as python script.py --output report.csv --format csv)
Comparison Table
| Feature | sys.argv |
argparse |
|---|---|---|
| Ease of use | Simple, no imports needed | Requires import, more setup |
| Named flags | Not supported | Full support (--output) |
| Default values | Manual handling | Built-in default= |
| Error handling | Manual | Automatic help messages |
| Best for | Quick scripts, one argument | Engineers needing robust CLI tools |
๐งญ Context Introduction
When building a system health reporter, you often need to save results to a file for later review or sharing. Rather than hardcoding a filename, you can let users specify their own output file at runtime using command-line flags. This makes your script flexible, reusable, and professional. In this section, you'll learn how to parse a command-line flag that lets users choose where to save their report.
โ๏ธ Why Use Command-Line Flags for Output Files?
- Flexibility: Users can save reports to different locations without editing the script.
- Automation: Other scripts or cron jobs can pass filenames dynamically.
- Clarity: The script's behavior is explicit and easy to understand.
- Reusability: One script works for multiple scenarios (daily reports, backups, etc.).
๐ ๏ธ How Flag Parsing Works
- Python's built-in argparse module handles command-line flag parsing.
- You define expected flags (like --output or -o) and their types.
- When the script runs, it reads the flags and stores the values in variables.
- If a required flag is missing, argparse automatically shows a helpful error message.
๐ Basic Structure for Output File Selection
Here is the typical flow for adding an output file flag:
- Import the argparse module at the top of your script.
- Create an ArgumentParser object with a description of your tool.
- Add an argument using add_argument() with the flag name (e.g., --output).
- Specify a short alias (e.g., -o) for convenience.
- Set the argument as a string type (the default).
- Parse the arguments with parse_args().
- Use the parsed value as your output filename.
๐งช Example Script Flow
Consider a simple system health reporter that collects CPU and memory usage:
- The script defines a flag called --output with alias -o.
- The user runs the script like this: python health_reporter.py --output report.txt
- Inside the script, the value report.txt is stored in args.output.
- The script then opens that file and writes the health data to it.
- If the user runs the script without the flag, argparse shows a friendly error reminding them to provide a filename.
๐งฉ Comparison: Hardcoded vs. Flag-Based Output
| Feature | Hardcoded Filename | Flag-Based Output |
|---|---|---|
| Flexibility | Low โ filename never changes | High โ user chooses each time |
| Automation | Requires manual edits | Works with cron and scripts |
| Error Handling | None built-in | Automatic missing flag messages |
| User Experience | Confusing for others | Clear and professional |
| Code Reusability | One-time use | Reusable across projects |
๐ต๏ธ Common Pitfalls to Avoid
- Forgetting to parse arguments: Always call parse_args() after defining all flags.
- Using the wrong variable name: The attribute name matches the flag name (e.g., --output becomes args.output).
- Not handling missing flags gracefully: Use required=True in add_argument() to enforce the flag.
- Overwriting existing files without warning: Consider adding a confirmation prompt or a --force flag.
- Mixing flag order: argparse handles any order, but keep your flags consistent for readability.
๐ง Key Takeaways
- Command-line flags make your scripts flexible and user-friendly.
- Python's argparse module handles all the heavy lifting for flag parsing.
- Always use descriptive flag names like --output for clarity.
- Test your script with and without flags to ensure proper error handling.
- A well-designed flag system makes your tool ready for automation and production use.
๐ Next Steps
- Practice adding an --output flag to a simple script that writes system information.
- Experiment with optional flags (e.g., --verbose or --format).
- Combine multiple flags to create a fully configurable health reporter.
- Test your script with different filenames and paths to confirm it works correctly.
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
This technique allows engineers to specify an output file path from the command line when running their Python script.
๐งช Example 1: Basic flag with sys.argv
This example shows how to read a command-line argument as a filename using the raw sys.argv list.
import sys
# Get the filename from command-line argument
filename = sys.argv[1]
print(f"Output will be saved to: {filename}")
๐ค Output: Output will be saved to: report.txt (when run as python script.py report.txt)
๐งช Example 2: Using argparse for a named flag
This example introduces the argparse module to define a --output flag.
import argparse
# Create the argument parser
parser = argparse.ArgumentParser()
# Add the --output flag
parser.add_argument("--output", help="Path to output file")
# Parse the arguments
args = parser.parse_args()
# Use the provided filename
output_file = args.output
print(f"Output file: {output_file}")
๐ค Output: Output file: results.txt (when run as python script.py --output results.txt)
๐งช Example 3: Default filename when no flag is given
This example shows how to set a default output filename when the user does not provide the flag.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--output", default="system_report.txt", help="Output file path")
args = parser.parse_args()
output_file = args.output
print(f"Output file: {output_file}")
๐ค Output: Output file: system_report.txt (when run as python script.py)
๐งช Example 4: Writing system health data to the chosen file
This example demonstrates writing actual content to the file specified by the --output flag.
import argparse
import datetime
parser = argparse.ArgumentParser()
parser.add_argument("--output", default="health_report.txt", help="Output file path")
args = parser.parse_args()
# Generate a simple health report
timestamp = datetime.datetime.now()
report_line = f"System health check at {timestamp}: All services running\n"
# Write to the chosen file
with open(args.output, "w") as f:
f.write(report_line)
print(f"Report written to: {args.output}")
๐ค Output: Report written to: health_report.txt (when run as python script.py --output health_report.txt)
๐งช Example 5: Combining multiple flags with output file selection
This example shows a more practical scenario where the engineer selects both output format and output file.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--output", default="report.txt", help="Output file path")
parser.add_argument("--format", choices=["text", "csv"], default="text", help="Output format")
args = parser.parse_args()
# Build content based on format choice
if args.format == "text":
content = "CPU: 45%\nMemory: 60%\nDisk: 80%"
elif args.format == "csv":
content = "metric,value\nCPU,45\nMemory,60\nDisk,80"
# Write to the chosen file
with open(args.output, "w") as f:
f.write(content)
print(f"Written {args.format} report to: {args.output}")
๐ค Output: Written csv report to: report.csv (when run as python script.py --output report.csv --format csv)
Comparison Table
| Feature | sys.argv |
argparse |
|---|---|---|
| Ease of use | Simple, no imports needed | Requires import, more setup |
| Named flags | Not supported | Full support (--output) |
| Default values | Manual handling | Built-in default= |
| Error handling | Manual | Automatic help messages |
| Best for | Quick scripts, one argument | Engineers needing robust CLI tools |