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