-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample.py
88 lines (72 loc) · 2.64 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
Example application showing Python 3.10 structural pattern matching.
"""
import shlex
from dataclasses import dataclass
from typing import List
def run_command_v1(command: str) -> None:
match command:
case "quit":
print("Quitting the program.")
case "reset":
print("Resetting the system.")
case other:
print(f"Unknown command '{other}'.")
def run_command_v2(command: str) -> None:
match command.split():
case ["load", filename]:
print(f"Loading filename {filename}.")
case ["save", filename]:
print(f"Saving filename {filename}.")
case ["quit" | "exit" | "bye", *rest]:
if "--force" in rest or "-f" in rest:
print("Sending SIGTERM to all processes and quitting the program.")
else:
print("Quitting the program.")
quit()
case _:
print(f"Unknown command '{command}'.")
def run_command_v3(command: str) -> None:
match command.split():
case ["load", filename]:
print(f"Loading filename {filename}.")
case ["save", filename]:
print(f"Saving filename {filename}.")
case ["quit" | "exit" | "bye", *rest] if "--force" in rest or "-f" in rest:
print("Sending SIGTERM to all processes and quitting the program.")
quit()
case ["quit" | "exit" | "bye"]:
print("Quitting the program.")
quit()
case _:
print(f"Unknown command {command!r}.")
@dataclass
class Command:
"""Class that represents a command."""
command: str
arguments: List[str]
def run_command_v4(command: Command) -> None:
match command:
case Command(command="load", arguments=[filename]):
print(f"Loading filename {filename}.")
case Command(command="save", arguments=[filename]):
print(f"Saving filename {filename}.")
case Command(command="quit" | "exit" | "bye", arguments=["--force" | "-f", *rest]):
print("Sending SIGTERM to all processes and quitting the program.")
quit()
case Command(command="quit" | "exit" | "bye"):
print("Quitting the program.")
quit()
case _:
print(f"Unknown command {command!r}.")
def main() -> None:
"""Main function."""
while True:
# command = input("$ ")
# run_command_v3(command)
# read a command with arguments from the input
command, *arguments = shlex.split(input("$ "))
# run the command
run_command_v4(Command(command, arguments))
if __name__ == "__main__":
main()