|
1 | | -import cowsay |
2 | 1 | import argparse |
3 | | -import sys |
4 | | -import os |
| 2 | +import cowsay |
| 3 | + |
| 4 | +def main(): |
| 5 | + # List of available animals (provided by the package) |
| 6 | + animals = cowsay.char_names |
| 7 | + |
| 8 | + parser = argparse.ArgumentParser( |
| 9 | + prog="cowsay", |
| 10 | + description="Make animals say things" |
| 11 | + ) |
| 12 | + |
| 13 | + parser.add_argument( |
| 14 | + "message", |
| 15 | + nargs="+", |
| 16 | + help="The message to say." |
| 17 | + ) |
5 | 18 |
|
6 | | -# Dynamically determine the cows directory |
7 | | -COWS_DIR = os.path.join(os.path.dirname(cowsay.__file__), "cows") |
| 19 | + parser.add_argument( |
| 20 | + "--animal", |
| 21 | + choices=animals, |
| 22 | + default="cow", |
| 23 | + help="The animal to be saying things." |
| 24 | + ) |
8 | 25 |
|
9 | | -# Set up argument parsing |
10 | | -parser = argparse.ArgumentParser() |
11 | | -parser.add_argument("--animal", required=True) |
12 | | -parser.add_argument("message", nargs="+") |
13 | | -args = parser.parse_args() |
| 26 | + args = parser.parse_args() |
14 | 27 |
|
15 | | -# Combine message parts into a single string |
16 | | -message = " ".join(args.message) |
| 28 | + message = " ".join(args.message) |
17 | 29 |
|
18 | | -# Dynamically fetch available animals |
19 | | -animals = [f[:-4] for f in os.listdir(COWS_DIR) if f.endswith(".cow")] |
| 30 | + # Dynamically call the function for the chosen animal |
| 31 | + animal_func = getattr(cowsay, args.animal) |
| 32 | + print(animal_func(message)) |
20 | 33 |
|
21 | | -# Validate the provided animal |
22 | | -if args.animal not in animals: |
23 | | - print("Error: '--animal' is not a valid cowsay animal.") |
24 | | - print("Available animals:", ", ".join(sorted(animals))) |
25 | | - sys.exit(1) |
26 | 34 |
|
27 | | -# Just pass the animal name directly |
28 | | -print(cowsay.cowsay(message, cow=args.animal)) |
| 35 | +if __name__ == "__main__": |
| 36 | + main() |
0 commit comments