|
1 | | -#!/usr/bin/env python3 |
2 | 1 | import argparse |
3 | 2 | import cowsay |
4 | 3 | import sys |
5 | 4 |
|
6 | | -def main(): |
7 | | - parser = argparse.ArgumentParser( |
8 | | - description="Make animals say things" |
9 | | - ) |
10 | | - parser.add_argument( |
11 | | - "message", nargs="+", help="The message to say." |
12 | | - ) |
13 | | - parser.add_argument( |
14 | | - "--animal", |
15 | | - default="cow", |
16 | | - help="The animal to be saying things." |
17 | | - ) |
18 | | - |
19 | | - args = parser.parse_args() |
20 | | - |
21 | | - text = " ".join(args.message) |
22 | | - animal = args.animal |
23 | | - |
24 | | - supported_animals = [ |
25 | | - "beavis", "cheese", "cow", "daemon", "dragon", "fox", |
26 | | - "ghostbusters", "kitty", "meow", "miki", "milk", "octopus", |
27 | | - "pig", "stegosaurus", "stimpy", "trex", "turkey", "turtle", "tux" |
28 | | - ] |
29 | | - |
30 | | - if animal not in supported_animals: |
31 | | - print(f"usage: cowsay [-h] [--animal {{{','.join(supported_animals)}}}] message [message ...]") |
32 | | - print(f"cowsay: error: argument --animal: invalid choice: '{animal}' (choose from {','.join(supported_animals)})") |
33 | | - sys.exit(1) |
34 | | - |
35 | | - output = cowsay.get_output_string(animal, text) |
36 | | - print(output) |
37 | | - |
38 | | -if __name__ == "__main__": |
39 | | - main() |
| 5 | +parser = argparse.ArgumentParser( |
| 6 | + prog="cowsay", |
| 7 | + description="Make animals say things" |
| 8 | +) |
| 9 | + |
| 10 | +parser.add_argument( |
| 11 | + "--animal", |
| 12 | + choices=cowsay.char_names, |
| 13 | + default="cow", |
| 14 | + help="The animal to be saying things." |
| 15 | +) |
| 16 | + |
| 17 | +parser.add_argument( |
| 18 | + "--list-animals", |
| 19 | + action="store_true", |
| 20 | + help="List available animals and exit." |
| 21 | +) |
| 22 | + |
| 23 | +parser.add_argument( |
| 24 | + "message", |
| 25 | + nargs="*", |
| 26 | + help="The message for the animal to say." |
| 27 | +) |
| 28 | + |
| 29 | +args = parser.parse_args() |
| 30 | + |
| 31 | +if args.list_animals: |
| 32 | + print("\n".join(cowsay.char_names)) |
| 33 | + sys.exit(0) |
| 34 | + |
| 35 | +if not args.message: |
| 36 | + parser.error("the following arguments are required: message") |
| 37 | + |
| 38 | +getattr(cowsay, args.animal)(" ".join(args.message)) |
0 commit comments