Add --output flag to write to file

This commit is contained in:
Lennie S.
2026-04-11 22:48:03 +00:00
parent 06110e1cb6
commit 0e7aa4727e

View File

@@ -1,6 +1,9 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Fibonacci sequence calculator with colored output.""" """Fibonacci sequence calculator with colored output."""
import argparse
import sys
# ANSI color codes # ANSI color codes
GREEN = "\033[32m" GREEN = "\033[32m"
CYAN = "\033[36m" CYAN = "\033[36m"
@@ -30,18 +33,26 @@ def fibonacci(n: int) -> int:
return b return b
if __name__ == "__main__": def main():
import sys parser = argparse.ArgumentParser(description="Fibonacci sequence calculator")
parser.add_argument("n", type=int, help="The position n in the Fibonacci sequence")
if len(sys.argv) != 2: parser.add_argument("--output", "-o", help="Write output to a file instead of stdout")
print(f"Usage: {sys.argv[0]} <n>") args = parser.parse_args()
sys.exit(1)
try: try:
n = int(sys.argv[1]) result = fibonacci(args.n)
except ValueError: except ValueError as e:
print(f"{RED}Error: '{sys.argv[1]}' is not a valid integer{RESET}") print(f"{RED}Error: {e}{RESET}")
sys.exit(1) sys.exit(1)
result = fibonacci(n) output_line = f"{CYAN}fibonacci({args.n}){RESET} {GREEN}={RESET} {GREEN}{result}{RESET}"
print(f"{CYAN}fibonacci({n}){RESET} {GREEN}={RESET} {GREEN}{result}{RESET}")
if args.output:
with open(args.output, "w") as f:
f.write(output_line + "\n")
else:
print(output_line)
if __name__ == "__main__":
main()