byzh-core 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,116 @@
1
+ import os
2
+ from pathlib import Path
3
+ import subprocess
4
+ import time
5
+
6
+ from ..Bbasic import B_Color
7
+
8
+
9
+ def args_process(args: tuple) -> list:
10
+ lst = []
11
+ for x in args:
12
+ if type(x) is str:
13
+ lst.append(x)
14
+ elif type(x) is list:
15
+ lst.extend(x)
16
+ return lst
17
+
18
+ def b_run_cmd(
19
+ *args: str,
20
+ show: bool = True,
21
+ ):
22
+ '''
23
+ 可传入多个字符串, 在cmd中运行
24
+ :param args:
25
+ :param show: 若show=True, 则会单开一个cmd, 在cmd中运行
26
+ :return:
27
+ '''
28
+ command = ''
29
+ for i in range(len(args)):
30
+ if i == len(args) - 1:
31
+ command += str(args[i])
32
+ break
33
+ command += str(args[i]) + ' && '
34
+ if show:
35
+ command = f'start cmd /K "{command}"'
36
+ # print(command)
37
+ subprocess.run(command, shell=True)
38
+
39
+ def b_run_python(
40
+ *args: str|list[str],
41
+ limit_time: int|float|None = None,
42
+ log_path: Path|None = None
43
+ ):
44
+ '''
45
+ 可传入多个字符串, 在当前python环境下运行
46
+ :param args: 以python开头, 用于运行.py文件
47
+ :param show:
48
+ :return:
49
+ '''
50
+ def run_log(content=''):
51
+ if log_path is not None:
52
+ parent = Path(log_path).parent
53
+ os.makedirs(parent, exist_ok=True)
54
+ with open(log_path, 'w', encoding='utf-8') as f:
55
+ f.write("=====================\n")
56
+ for string in str_lst:
57
+ f.write("\t" + string + '\n')
58
+ f.write("=====================\n")
59
+ f.write(content)
60
+
61
+ str_lst = args_process(args)
62
+
63
+ print(f"{B_Color.GREEN}=====================")
64
+ print("BRunPython 将在3秒后开始:")
65
+ for string in str_lst:
66
+ print("\t" + string)
67
+ print(f"====================={B_Color.RESET}")
68
+ time.sleep(3)
69
+
70
+ for string in str_lst:
71
+ try:
72
+ command_lst = string.split(' ')
73
+ run_log("正在执行: " + string)
74
+ start = time.time()
75
+ result = subprocess.run(command_lst, timeout=limit_time)
76
+ end = time.time()
77
+ delta_t = end - start
78
+ h_t = int(delta_t // 3600)
79
+ m_t = int((delta_t % 3600) // 60)
80
+ s_t = int(delta_t % 60)
81
+ if result.returncode != 0: # 报错
82
+ index = str_lst.index(string)
83
+ str_lst[index] = string + f"\t[!!!Error!!!] [{h_t}h {m_t}m {s_t}s]"
84
+ else:
85
+ index = str_lst.index(string)
86
+ str_lst[index] = string + f"\t[~Success~] [{h_t}h {m_t}m {s_t}s]"
87
+ except subprocess.TimeoutExpired:
88
+ print(f"程序运行超过 {limit_time} 秒,已被强制终止")
89
+ h_t = int(limit_time // 3600)
90
+ m_t = int((limit_time % 3600) // 60)
91
+ s_t = int(limit_time % 60)
92
+ index = str_lst.index(string)
93
+ str_lst[index] = string + f"\t[!!!Time limit!!!] [{h_t}h {m_t}m {s_t}s]"
94
+
95
+ print(f"{B_Color.GREEN}====================={B_Color.RESET}")
96
+ print(f"{B_Color.GREEN}BRunPython 结束:{B_Color.RESET}")
97
+ for string in str_lst:
98
+ if 'Time limit' in string:
99
+ print(f"\t{B_Color.YELLOW}" + string + f"{B_Color.RESET}")
100
+ elif 'Error' in string:
101
+ print(f"\t{B_Color.RED}" + string + f"{B_Color.RESET}")
102
+ else:
103
+ print(f"\t{B_Color.GREEN}" + string + f"{B_Color.RESET}")
104
+ print(f"{B_Color.GREEN}====================={B_Color.RESET}")
105
+
106
+ run_log('结束')
107
+
108
+
109
+
110
+ if __name__ == '__main__':
111
+ b_run_cmd("echo hello", "echo world", "echo awa", show=True)
112
+ # b_run_python(
113
+ # r"python E:\byzh_workingplace\byzh-rc-to-pypi\test1.py",
114
+ # r"python E:\byzh_workingplace\byzh-rc-to-pypi\test2.py",
115
+ # limit_time=3,
116
+ # )
@@ -0,0 +1,4 @@
1
+
2
+ from .b_tqdm import B_Tqdm
3
+
4
+ __all__ = ['B_Tqdm']
@@ -0,0 +1,76 @@
1
+ import sys
2
+ import time
3
+
4
+ from ..Bbasic import B_Color
5
+
6
+
7
+ class B_Tqdm:
8
+ def __init__(
9
+ self,
10
+ total: int|None = None,
11
+ prefix: str = 'Processing',
12
+ suffix: str = '',
13
+ length: int = 20,
14
+ fill: str = '█',
15
+ ):
16
+ """
17
+ 类似tqdm的进度条
18
+ :param total: 总数
19
+ :param prefix: 前缀
20
+ :param suffix: 后缀
21
+ :param length: 进度条长度(字符)
22
+ :param fill: 填充字符
23
+ """
24
+ super().__init__()
25
+ self.total = total
26
+ self.prefix = prefix
27
+ self.suffix = suffix
28
+ self.length = length
29
+ self.fill = fill
30
+ self.start_time = 0
31
+ self.current = 0
32
+
33
+ def _format_time(self, seconds):
34
+ """将秒数转换为mm:ss格式"""
35
+ minutes = int(seconds // 60)
36
+ seconds = int(seconds % 60)
37
+ return f'{minutes:02}:{seconds:02}'
38
+
39
+ def update(self, step=1, color=B_Color.BLUE, prefix=None, suffix=None):
40
+ if self.current == 0:
41
+ self.start_time = time.time()
42
+ if prefix is not None:
43
+ self.prefix = prefix
44
+ if suffix is not None:
45
+ self.suffix = suffix
46
+
47
+ # 更新进度
48
+ self.current += step
49
+
50
+ # 计算已用时间
51
+ elapsed_time = time.time() - self.start_time
52
+ elapsed_str = self._format_time(elapsed_time)
53
+ # 预估剩余时间
54
+ if self.total is not None:
55
+ estimated_time = elapsed_time / self.current * (self.total - self.current) if self.current > 0 else 0
56
+ estimated_str = self._format_time(estimated_time)
57
+ # 计算每秒处理的项数
58
+ speed = self.current / elapsed_time if elapsed_time > 0 else 0
59
+
60
+ # 更新进度条
61
+ if self.total is not None:
62
+ filled_length = int(self.length * self.current // self.total)
63
+ bar = self.fill * filled_length + '-' * (self.length - filled_length)
64
+
65
+ sys.stdout.write(f'\r{color}{self.prefix} |{bar}|'
66
+ f' {self.current}/{self.total} -> {elapsed_str}<{estimated_str} | {speed:.1f} it/s |'
67
+ f' {self.suffix}{B_Color.RESET}')
68
+ else:
69
+ sys.stdout.write(f'\r{color}{self.prefix} | {self.current} iters -> {elapsed_str} | {speed:.1f} it/s |'
70
+ f' {self.suffix}{B_Color.RESET}')
71
+ sys.stdout.flush()
72
+
73
+ # 补回车
74
+ if self.current == self.total:
75
+ sys.stdout.write('\n')
76
+ sys.stdout.flush()
@@ -0,0 +1,5 @@
1
+
2
+ from .writer import B_Writer
3
+ from .globalwriter import B_GlobalWriter
4
+
5
+ __all__ = ['B_Writer', 'B_GlobalWriter']
@@ -0,0 +1,62 @@
1
+ import threading
2
+ import time
3
+ import atexit
4
+
5
+
6
+ class B_GlobalWriter():
7
+ _instance = None
8
+ _lock = threading.Lock()
9
+
10
+ def __new__(cls):
11
+ if cls._instance is None:
12
+ with cls._lock:
13
+ if cls._instance is None:
14
+ cls._instance = super().__new__(cls)
15
+ # 初始化
16
+ cls._instance.file = None
17
+ cls._instance.f = None
18
+ cls._instance.ifTime = False
19
+ atexit.register(cls._instance.closeFile) # 注册关闭方法
20
+ return cls._instance
21
+
22
+ @classmethod
23
+ def setFile(cls, file, ifTime=False):
24
+ cls()
25
+ cls._instance.ifTime = ifTime
26
+ cls._instance.path = file
27
+ cls._instance.f = open(cls._instance.path, "a", encoding="utf-8")
28
+
29
+ @classmethod
30
+ def clearFile(cls):
31
+ cls()
32
+ assert cls._instance.f is not None, "请先调用setFile方法"
33
+ cls._instance.f.close()
34
+ cls._instance.f = open(cls._instance.path, 'w', encoding="utf-8")
35
+
36
+ @classmethod
37
+ def closeFile(cls):
38
+ if cls._instance.f:
39
+ cls._instance.f.close()
40
+ cls._instance.f = None
41
+
42
+ @classmethod
43
+ def toCmd(cls, string):
44
+ cls()
45
+ print(string)
46
+
47
+ @classmethod
48
+ def toFile(cls, string):
49
+ cls()
50
+ assert cls._instance.f is not None, "请先调用setFile方法"
51
+ if cls._instance.ifTime:
52
+ t = time.strftime("%Y-%m-%d %H:%M:%S ##### ", time.localtime())
53
+ cls._instance.f.write(t)
54
+ cls._instance.f.write(string)
55
+ cls._instance.f.write("\n")
56
+ cls._instance.f.flush()
57
+
58
+ @classmethod
59
+ def toBoth(cls, string):
60
+ cls()
61
+ cls.toFile(string)
62
+ cls.toCmd(string)
@@ -0,0 +1,138 @@
1
+ from pathlib import Path
2
+ from typing import Literal
3
+ import time
4
+ import os
5
+
6
+ from ..Bbasic import B_Color
7
+
8
+ COLOR_DICT = {
9
+ "default": B_Color.RESET,
10
+
11
+ "black": B_Color.BLACK,
12
+ "red": B_Color.RED,
13
+ "green": B_Color.GREEN,
14
+ "yellow": B_Color.YELLOW,
15
+ "blue": B_Color.BLUE,
16
+ "purple": B_Color.PURPLE,
17
+ "cyan": B_Color.CYAN,
18
+ "silver": B_Color.SILVER
19
+ }
20
+ Color_Literal = Literal["default", "black", "red", "green", "yellow", "blue", "purple", "cyan", "silver"]
21
+
22
+ class B_Writer:
23
+ def __init__(
24
+ self,
25
+ path: Path,
26
+ ifTime: bool = False,
27
+ color: Color_Literal = 'default',
28
+ ):
29
+ '''
30
+ :param path: 日志保存路径
31
+ :param ifTime: 是否输出时间
32
+ '''
33
+ super().__init__()
34
+ self.path = Path(path)
35
+ self.ifTime = ifTime
36
+ self.toWant_file = False
37
+ self.toWant_cmd = False
38
+
39
+ self.__checkColor(color)
40
+ self.color = color
41
+
42
+ self.f = None
43
+ self.setFile(self.path, self.ifTime)
44
+
45
+ def setFile(self, file: Path, ifTime=False):
46
+ '''
47
+ 设置 file的path 以及 writer的ifTime
48
+ :param file: 设置log路径
49
+ :param ifTime:
50
+ :return:
51
+ '''
52
+ if self.f is not None:
53
+ self.f.close()
54
+ self.path = Path(file)
55
+ self.ifTime = ifTime
56
+ self.__createDir(self.path)
57
+ self.f = open(self.path, "a", encoding="utf-8")
58
+
59
+ def clearFile(self):
60
+ '''
61
+ 清空内容
62
+ '''
63
+ assert self.f is not None, "请先调用setFile方法"
64
+ self.f.close()
65
+ self.f = open(self.path, 'w', encoding="utf-8")
66
+
67
+ def closeFile(self):
68
+ '''
69
+ 关闭log
70
+ '''
71
+ if self.f:
72
+ self.f.close()
73
+ self.f = None
74
+
75
+ def toCmd(self, string, color: Color_Literal = None):
76
+ '''
77
+ 打印到terminal
78
+ '''
79
+ # 检查color是否在字典中
80
+ if color is None:
81
+ print(COLOR_DICT.get(self.color) + str(string) + B_Color.RESET)
82
+ else:
83
+ assert color in COLOR_DICT, f"color参数错误,请输入{COLOR_DICT.keys()}"
84
+ print(COLOR_DICT.get(color) + str(string) + B_Color.RESET)
85
+
86
+ def toFile(self, string, ifTime=None):
87
+ '''
88
+ 写入到文件内
89
+ '''
90
+ assert self.f is not None, "请先调用setFile方法"
91
+
92
+ if ifTime == False:
93
+ pass
94
+ elif ifTime==True or self.ifTime==True:
95
+ t = time.strftime("%Y-%m-%d %H:%M:%S ##### ", time.localtime())
96
+ self.f.write(t)
97
+
98
+ self.f.write(str(string))
99
+ self.f.write("\n")
100
+ self.f.flush()
101
+
102
+ def toBoth(self, string, ifTime=False, color: Color_Literal = None):
103
+ '''
104
+ 同时写入到文件和terminal
105
+ :param string:
106
+ :param color:
107
+ :return:
108
+ '''
109
+ self.toFile(str(string), ifTime)
110
+ self.toCmd(str(string), color)
111
+
112
+ def setWant(self, toCmd=False, toFile=False):
113
+ '''
114
+ toWant的全局选项设置
115
+ '''
116
+ self.toWant_cmd = toCmd
117
+ self.toWant_file = toFile
118
+
119
+ def toWant(self, string, ifTime=False, color: Color_Literal = None):
120
+ '''
121
+ 使用前先调用setWant方法
122
+ '''
123
+ if self.toWant_cmd and self.toWant_file:
124
+ self.toBoth(string, ifTime, color)
125
+ elif self.toWant_cmd:
126
+ self.toCmd(string, color)
127
+ elif self.toWant_file:
128
+ self.toFile(string, ifTime)
129
+ else:
130
+ raise Exception("请先调用setWant方法, 设置toCmd或toFile为True")
131
+
132
+ def __checkColor(self, color):
133
+ assert color in COLOR_DICT, f"color参数错误,请输入{list(COLOR_DICT.keys())}"
134
+
135
+ def __createDir(self, path):
136
+ # 获取到该文件的文件夹
137
+ dir = path.parents[0]
138
+ os.makedirs(dir, exist_ok=True)
byzh_core/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ # package 以"B"开头
2
+ # class 以"B_"开头
3
+ # function 以"b_"开头
4
+
5
+ __version__ = '0.0.1'
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [2024] [zhengyu]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.1
2
+ Name: byzh_core
3
+ Version: 0.0.1
4
+ Summary: byzh_core是byzh系列的核心库,包含了一些常用的工具函数和类。
5
+ Author: byzh_rc
6
+ License: MIT
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: wcwidth
10
+
11
+ # progressBar.py
12
+ just like tqdm
13
+
14
+ # log.py
15
+ jsut like loguru
16
+
17
+ # train.py
18
+ provide Trainer
@@ -0,0 +1,28 @@
1
+ byzh_core/__init__.py,sha256=UkNGyvELAvNTWs8-DnCFe4RDLkKKHYzpUKoEVT--V48,108
2
+ byzh_core/Barchive/__init__.py,sha256=wUdz646VS0Uhq9lwMkd3YQHCvQhLDqgADoDjFGMqIn0,65
3
+ byzh_core/Barchive/archive.py,sha256=yIQgef1APUcZdHM_7Pa9rCam-P3PA3pbcSJSaySoUj4,2498
4
+ byzh_core/Bbasic/__init__.py,sha256=wr7Y7YJINhgpV5X6BT5DaGJKcHUOZYNerCGXoi2Egac,116
5
+ byzh_core/Bbasic/text_style.py,sha256=JelgL3AgcH607Mr-Bvr4u8Svb0twmNmqwXvOl4hHOSs,3161
6
+ byzh_core/Bconfig/__init__.py,sha256=7lAp7wNetW0AyJcike7ekdY_8wrQQtFjBsi6684t_lU,54
7
+ byzh_core/Bconfig/config.py,sha256=P9C4kAkxKnIFaJCErBXdABfOyWgFgVHpR-i-fiZXCNs,10956
8
+ byzh_core/Bmath/__init__.py,sha256=G3AQug6izkEX3UfzO_mqUNJW88ZKlmYb4Q8CAactK4w,105
9
+ byzh_core/Bmath/divides.py,sha256=dr85IqGSE9NvugQu7az29GLcjRiLjXU_hZTwtNifIXg,1132
10
+ byzh_core/Bmath/get_norm.py,sha256=y1QsCTo7qhtGTXIxpc6JtamLWloC7ENRuVdNtK5yi58,596
11
+ byzh_core/Btable/__init__.py,sha256=wpfHMPD4awPRDJVYlaiGtkkpjq2srWB7d7LrWhoX5R0,161
12
+ byzh_core/Btable/auto_table.py,sha256=JREmn6KIlZKkv1Vsc23Ow3fDiJAgfMppbGKDUY8rfyk,14002
13
+ byzh_core/Btable/row_table.py,sha256=rIX0-Yvb3RnO0RJBkA4m18gux1zYSnEKTy6uQGcWilc,5999
14
+ byzh_core/Btable/xy_table.py,sha256=-KHK8EUlkJj3Rh0sp_KHI0QFt29AlMASMmR8q8ykUBM,6784
15
+ byzh_core/Btable/obsolete/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ byzh_core/Btable/obsolete/b_auto_table.py,sha256=Cmblv_pknQeMew_KLO8vGdeSRtAykwbMh30QVhgS3UI,10422
17
+ byzh_core/Bterminal/__init__.py,sha256=B6p6mHVhi5LAHKlvqfrv20E6XNqUsfU2xD753V6-Zf4,83
18
+ byzh_core/Bterminal/cmd.py,sha256=iK0fwI0D3peEwUYYZWwnl9X8ImFfrBsEq6ySd3DcRdE,3839
19
+ byzh_core/Btqdm/__init__.py,sha256=wyVbj7X1YpMeGJlriwISV-blZj4hfAk4ihpPMrUR8a0,52
20
+ byzh_core/Btqdm/b_tqdm.py,sha256=692mfNqXhCwXunIpIMNVDt-5GRz4XMVCbcbiM4F9WGM,2620
21
+ byzh_core/Bwriter/__init__.py,sha256=KSsbCJZ-1j5wOr-ZbTg8K3A8Du73d22DQVLdmq-3CBo,116
22
+ byzh_core/Bwriter/globalwriter.py,sha256=tSjWxzLylAeZep67n5jbRsjQkXkBKRZLvKXUyGSY92Q,1824
23
+ byzh_core/Bwriter/writer.py,sha256=px0ZNoSuXS_RbwVnYsBx2lYohyhHACfHM8-HBNEflhU,4006
24
+ byzh_core-0.0.1.dist-info/LICENSE,sha256=-nRwf0Xga4AX5bsWBXXflpDpgX_U23X06oAMcdf0dSY,1089
25
+ byzh_core-0.0.1.dist-info/METADATA,sha256=sjh9E-FrWF2_82hv2RqEbVsy1lM3OyH-mKUy_JzVjYc,365
26
+ byzh_core-0.0.1.dist-info/WHEEL,sha256=R0nc6qTxuoLk7ShA2_Y-UWkN8ZdfDBG2B6Eqpz2WXbs,91
27
+ byzh_core-0.0.1.dist-info/top_level.txt,sha256=Xv-pzvl6kPdIbi5UehQcUdGhLtb8-4WhS5dRK1LINwM,10
28
+ byzh_core-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (72.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ byzh_core