-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmenu_tools.py
70 lines (57 loc) · 1.79 KB
/
menu_tools.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
import os
import re
from typing import Callable
import dumb_menu
def _show_clean_menu(options, selected_index):
os.system("cls" if os.name == "nt" else "clear")
for i, option in enumerate(options):
if isinstance(option, dict):
if option.get("__title__"):
print(option["__title__"])
for i, option in enumerate(options):
if isinstance(option, dict):
continue
if i == selected_index:
print(f"> {option}")
else:
print(f" {option}")
def _scan_short_cuts(options):
shortcuts = {}
for i, option in enumerate(options):
if isinstance(option, dict):
continue
match = re.match(r"\[(.*)\](.*)", option)
if match:
shortcut, text = match.group(1, 2)
shortcuts[shortcut] = i
return shortcuts
dumb_menu.show_clean_menu = _show_clean_menu
dumb_menu.scan_short_cuts = _scan_short_cuts
class MenuTools:
"""
例子
MenuTools(
title="---这是标题---",
options={
test1: "这是选项1",
test2: "这是选项2",
},
args={test2: {"arg3": 123}},
).show()
"""
def __init__(
self, options: dict[str, Callable], args=None, title: str = None
) -> None:
self.options = options
self.args = args if args is not None else {}
self.title = title
def show(self):
menu_options = list(self.options.values())
if self.title is not None:
menu_options.append({"__title__": self.title})
self.index = dumb_menu.get_menu_choice(menu_options, True)
func = list(self.options.keys())[self.index]
if func in self.args.keys():
return func(**self.args[func])
else:
return func()