-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmt.py
More file actions
221 lines (177 loc) · 7.1 KB
/
mt.py
File metadata and controls
221 lines (177 loc) · 7.1 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import os
import sys
from typing import Any, Callable, Union
test_env: bool = os.path.exists('.test_env')
venv: bool = hasattr(sys, 'real_prefix') or (
hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
current_path: str = os.path.abspath(
os.path.join(os.path.abspath(__file__), os.pardir))
windows: bool = os.name == 'nt'
path: str = 'Y:/3BHIT/test/' if not test_env else os.path.join(
current_path, 'test')
if test_env and not os.path.exists(path):
os.makedirs(path)
def y_n(inp: str, allow_empty: bool = False) -> bool:
if inp is not None:
print(inp, end=' ')
res: str = input().strip().lower()
if allow_empty and res == '':
return False
return res == 'y' or res == 'j'
def ensure_venv(file: str, args: list[str] = []) -> None:
if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
pass
else:
if test_env:
if windows:
os.system(
f'.\\.venv\\Scripts\\activate.bat && python "{file}" {" ".join(args)}')
else:
os.system(
f'source .venv/bin/activate && python "{file}" {" ".join(args)}')
else:
os.system(
f"Z: && cd Z:\\Documents\\moritz_tools && .\\.venv\\Scripts\\activate.bat && python {file} {' '.join(args)}")
exit()
def better_input(prompt: str, min_len: int = 0, max_len: int = 0, allow_spaces: bool = True, silent: bool = False, allow_empty: bool = False, halal: bool = True) -> str:
inp: Union[str, None] = None
while not check_str(inp, min_len, max_len, allow_spaces, silent, allow_empty, halal):
inp = input(prompt).strip()
return str(inp)
def better_getpass(prompt: str, min_len: int = 0, max_len: int = 0, allow_spaces: bool = True, silent: bool = False, allow_empty: bool = False, halal: bool = True) -> str:
from getpass import getpass
inp: Union[str, None] = None
while not check_str(inp, min_len, max_len, allow_spaces, silent, allow_empty, halal):
inp = getpass(prompt).strip()
return str(inp)
def check_str(inp: Union[str, None], min_len: int = 0, max_len: int = 0, allow_spaces: bool = True, silent: bool = False, allow_empty: bool = False, halal: bool = True) -> bool:
if inp is None:
return False
if inp == '' and allow_empty:
return True
if halal and ('neg' in inp.lower() or 'nig' in inp.lower()):
return False
if len(inp) < min_len:
if not silent:
print('Eingabe zu kurz')
return False
if max_len > 0 and len(inp) > max_len:
if not silent:
print('Eingabe zu lang')
return False
if not allow_spaces and ' ' in inp:
if not silent:
print('Eingabe enthält Abstände')
return False
return True
def type_input(prompt: str, type: type, allow_empty: bool = False) -> Any:
inp: str = input(prompt).strip()
if allow_empty and inp == '':
return False
try:
return type(inp)
except ValueError:
return type_input(prompt, type)
def popup(title: str, prompt: str) -> None:
if windows:
import ctypes
ctypes.windll.user32.MessageBoxW( # type: ignore
None, prompt, title, 0)
else:
import subprocess
applescript: str = f"""
display dialog "{prompt}" ¬
with title "{title}" ¬
with icon caution ¬
buttons {{"OK"}}
"""
subprocess.call(f"osascript -e '{applescript}'", shell=True)
def fix_res() -> None:
import ctypes
if windows:
ctypes.windll.shcore.SetProcessDpiAwareness(1) # type: ignore
def add_sth_sc() -> None:
from context_menu import menus
from sys import executable
fc = menus.FastCommand('Send To Home', type='FILES',
command=f'Z: && cd Z:\\Documents\\moritz_tools && "{executable}" "Z:\\Documents\\moritz_tools\\send_to_home_sc.py" ?', command_vars=['FILENAME'])
fc.compile()
fc2 = menus.FastCommand('Send To Home', type='DIRECTORY',
command=f'Z: && cd Z:\\Documents\\moritz_tools && "{executable}" "Z:\\Documents\\moritz_tools\\send_to_home_sc.py" ?', command_vars=['FILENAME'])
fc2.compile()
def generate_random_string(length: int) -> str:
import string
import random
letters: str = string.ascii_letters + string.digits
return ''.join(random.choice(letters) for _ in range(length))
def Webhook(url: str, content: Callable) -> None:
from requests import post
post(url, json={'content': f'{content()} {content}'})
def deprecated(name: str) -> None:
if name == '__main__':
from papertools import Console
Console.print_colour(
'Dieses Programm funktioniert nicht mehr so wie vorher und ist nun ein Teil von main.py. Führe main.py aus um das Programm weiterhin zu benutzen.', 'red')
input()
exit()
class Config:
def __init__(self) -> None:
from papertools import File
self.file: File = File('config.json')
self.check_cfg()
self.cfg: dict[str, Any] = self.file.json_r()
def check_cfg(self) -> None:
if not self.file.exists():
print('Config Datei nicht gefunden, wird neu erstellt')
self.file.json_w({})
try:
self.cfg: dict[str, Any] = self.file.json_r()
except Exception as e:
print(f'Fehler beim Lesen der Config Datei: {e}')
input()
exit()
def read(self) -> dict[str, Any]:
self.cfg = self.file.json_r()
return self.cfg
def write(self, cfg: Union[dict[str, Any], None] = None) -> None:
if cfg is not None:
self.cfg = cfg
self.file.json_w(self.cfg)
def smart_get(self, inp: str, path: str, **kwargs) -> Any:
if inp.strip() == '':
try:
return self.get_value_from_path(path)
except:
if kwargs.get('error_callback') != None:
kwargs['error_callback'](**kwargs)
return ''
else:
try:
self.get_value_from_path(path)
except:
self.write_value_to_path(path, inp)
return inp
def get_value_from_path(self, path: str) -> Any:
keys: list[str] = path.strip('/').split('/')
value: Any = self.cfg
for key in keys:
value = value[key]
return value
def write_value_to_path(self, path: str, value: Any, save: bool = True) -> None:
keys: list[str] = path.strip('/').split('/')
d: dict[str, Any] = self.cfg
for key in keys[:-1]:
if key not in d or not isinstance(d[key], dict):
d[key] = {}
d = d[key]
d[keys[-1]] = value
if save:
self.write()
def run_as_admin() -> None:
import sys
if len(sys.argv) >= 2 and sys.argv[1].strip() == 'admin':
return
import ctypes
ctypes.windll.shell32.ShellExecuteW(None, "runas", # type: ignore
sys.executable, f'"{sys.argv[0]}" admin', None, 1)
sys.exit()