byzh-core 0.0.7.0__tar.gz → 0.0.9.0__tar.gz
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.
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/PKG-INFO +2 -2
- byzh_core-0.0.9.0/byzh/core/B_os.py +157 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Brecorder/record1d.py +1 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Brecorder/record2d.py +32 -33
- byzh_core-0.0.9.0/byzh/core/__init__.py +0 -0
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/byzh_core.egg-info/PKG-INFO +2 -2
- byzh_core-0.0.9.0/byzh_core.egg-info/SOURCES.txt +29 -0
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/setup.py +1 -1
- byzh_core-0.0.7.0/byzh/obsolete/Bconfig/__init__.py +0 -3
- byzh_core-0.0.7.0/byzh/obsolete/Bconfig/config.py +0 -328
- byzh_core-0.0.7.0/byzh/obsolete/__init__.py +0 -6
- byzh_core-0.0.7.0/byzh/obsolete/auto_table.py +0 -427
- byzh_core-0.0.7.0/byzh/obsolete/row_table.py +0 -175
- byzh_core-0.0.7.0/byzh/obsolete/xy_table.py +0 -211
- byzh_core-0.0.7.0/byzh_core.egg-info/SOURCES.txt +0 -33
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/LICENSE +0 -0
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/README.md +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Barchive/__init__.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Barchive/archive.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Brecorder/__init__.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Btable/__init__.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Btable/auto_table.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Bterminal/__init__.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Bterminal/cmd.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Bterminal/run_func.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Btqdm/__init__.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Btqdm/my_tqdm.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Butils/__init__.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Butils/decorator.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Butils/text_style.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Butils/timer.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Bwriter/__init__.py +0 -0
- {byzh_core-0.0.7.0/byzh → byzh_core-0.0.9.0/byzh/core}/Bwriter/writer.py +0 -0
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/byzh_core.egg-info/dependency_links.txt +0 -0
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/byzh_core.egg-info/entry_points.txt +0 -0
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/byzh_core.egg-info/requires.txt +0 -0
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/byzh_core.egg-info/top_level.txt +0 -0
- {byzh_core-0.0.7.0 → byzh_core-0.0.9.0}/setup.cfg +0 -0
@@ -0,0 +1,157 @@
|
|
1
|
+
import shutil
|
2
|
+
import os
|
3
|
+
from pathlib import Path
|
4
|
+
|
5
|
+
from .Butils import b_validate_params
|
6
|
+
|
7
|
+
@b_validate_params({
|
8
|
+
"path": __file__
|
9
|
+
})
|
10
|
+
def get_parent_dir(path) -> Path:
|
11
|
+
'''
|
12
|
+
获取 该py文件 所在的文件夹
|
13
|
+
:param path: __file__
|
14
|
+
'''
|
15
|
+
parent_dir = Path(path).parent
|
16
|
+
return parent_dir
|
17
|
+
|
18
|
+
def get_cwd() -> Path:
|
19
|
+
'''
|
20
|
+
获取 当前工作目录current working directory
|
21
|
+
'''
|
22
|
+
return Path.cwd()
|
23
|
+
|
24
|
+
|
25
|
+
def makedirs(path):
|
26
|
+
def is_dir(path):
|
27
|
+
path = Path(path)
|
28
|
+
|
29
|
+
# 存在
|
30
|
+
if os.path.isdir(path):
|
31
|
+
return True
|
32
|
+
|
33
|
+
# 不存在
|
34
|
+
name = path.name
|
35
|
+
if '.' in name:
|
36
|
+
return False
|
37
|
+
return True
|
38
|
+
|
39
|
+
def is_file(path):
|
40
|
+
path = Path(path)
|
41
|
+
|
42
|
+
# 存在
|
43
|
+
if os.path.isfile(path):
|
44
|
+
return True
|
45
|
+
|
46
|
+
# 不存在
|
47
|
+
name = path.name
|
48
|
+
if '.' in name:
|
49
|
+
return True
|
50
|
+
return False
|
51
|
+
|
52
|
+
path = Path(path)
|
53
|
+
|
54
|
+
if is_dir(path):
|
55
|
+
os.makedirs(path, exist_ok=True)
|
56
|
+
if is_file(path):
|
57
|
+
os.makedirs(path.parent, exist_ok=True)
|
58
|
+
|
59
|
+
def makefile(path):
|
60
|
+
path = Path(path)
|
61
|
+
|
62
|
+
parent_dir = path.parent
|
63
|
+
makedirs(parent_dir)
|
64
|
+
|
65
|
+
path.touch() # 创建文件
|
66
|
+
|
67
|
+
def rm(path):
|
68
|
+
if os.path.isdir(path):
|
69
|
+
shutil.rmtree(path)
|
70
|
+
if os.path.isfile(path):
|
71
|
+
os.remove(path)
|
72
|
+
|
73
|
+
|
74
|
+
def get_dirpaths_in_dir(root_dir_path, exclude_dir=['__pycache__', '.git']):
|
75
|
+
result = []
|
76
|
+
for root, dirs, files in os.walk(root_dir_path):
|
77
|
+
for i, dir in enumerate(dirs):
|
78
|
+
if str(dir) in exclude_dir:
|
79
|
+
dirs.pop(i)
|
80
|
+
path = Path(root)
|
81
|
+
result.append(path)
|
82
|
+
|
83
|
+
result = result[1:]
|
84
|
+
|
85
|
+
return result
|
86
|
+
|
87
|
+
def get_filepaths_in_dir(root_dir_path, exclude_name=[], exclude_suffix=['.pyc'], exclude_dir=['.git']):
|
88
|
+
file_paths = []
|
89
|
+
for root, dirs, files in os.walk(root_dir_path):
|
90
|
+
for i, dir in enumerate(dirs):
|
91
|
+
if str(dir) in exclude_dir:
|
92
|
+
dirs.pop(i)
|
93
|
+
for file in files:
|
94
|
+
file_path = os.path.join(root, file)
|
95
|
+
file_path = Path(file_path)
|
96
|
+
if file_path.name in exclude_name or file_path.suffix in exclude_suffix:
|
97
|
+
continue
|
98
|
+
file_paths.append(file_path)
|
99
|
+
return file_paths
|
100
|
+
|
101
|
+
@b_validate_params({
|
102
|
+
"black_dirnames": {"examples": ["__pycache__", ".git"]},
|
103
|
+
"black_filenames": {"examples": ["__init__.py", "test.py"]},
|
104
|
+
"black_stems": {"examples": ["test", "example"]},
|
105
|
+
"black_exts": {"examples": [".pyc"]}
|
106
|
+
})
|
107
|
+
def walk(
|
108
|
+
root: str,
|
109
|
+
black_dirnames: list[str] = None,
|
110
|
+
black_filenames: list[str] = None,
|
111
|
+
black_stems: list[str] = None,
|
112
|
+
black_exts: list[str] = None,
|
113
|
+
):
|
114
|
+
"""
|
115
|
+
遍历目录, 类似os.walk, 但可以指定黑名单
|
116
|
+
:param root:
|
117
|
+
:param black_dirnames:
|
118
|
+
:param black_stems: 文件名
|
119
|
+
:param black_stems: 文件名, 不包括后缀
|
120
|
+
:param black_exts: 文件名的后缀(含.)
|
121
|
+
:return: root, dirs, files
|
122
|
+
"""
|
123
|
+
|
124
|
+
def get_lst(lst):
|
125
|
+
return [] if lst is None else lst
|
126
|
+
black_dirnames = get_lst(black_dirnames)
|
127
|
+
black_filenames = get_lst(black_filenames)
|
128
|
+
black_stems = get_lst(black_stems)
|
129
|
+
black_exts = get_lst(black_exts)
|
130
|
+
|
131
|
+
dirs = []
|
132
|
+
files = []
|
133
|
+
for entry in os.listdir(root):
|
134
|
+
path = os.path.join(root, entry)
|
135
|
+
# 是文件夹
|
136
|
+
if os.path.isdir(path):
|
137
|
+
dirs.append(entry)
|
138
|
+
# 是文件
|
139
|
+
elif os.path.isfile(path):
|
140
|
+
files.append(entry)
|
141
|
+
else:
|
142
|
+
continue
|
143
|
+
dirs = [d for d in dirs if d not in black_dirnames]
|
144
|
+
files = [f for f in files if f not in black_filenames]
|
145
|
+
files = [f for f in files if os.path.splitext(f)[0] not in black_stems]
|
146
|
+
files = [f for f in files if os.path.splitext(f)[1] not in black_exts]
|
147
|
+
|
148
|
+
yield root, dirs, files
|
149
|
+
|
150
|
+
for dirname in dirs:
|
151
|
+
new_path = os.path.join(root, dirname)
|
152
|
+
yield from walk(new_path, black_dirnames, black_filenames, black_stems, black_exts)
|
153
|
+
|
154
|
+
if __name__ == '__main__':
|
155
|
+
# print(get_dirpaths_in_dir(r'E:\byzh_workingplace\byzh-rc-to-pypi'))
|
156
|
+
a = get_filepaths_in_dir(r'/')
|
157
|
+
print(a)
|
@@ -15,39 +15,39 @@ class B_Record2d:
|
|
15
15
|
elif mode == "a":
|
16
16
|
self.__read()
|
17
17
|
|
18
|
-
|
19
|
-
|
18
|
+
# 支持 recorder[row, col] 访问
|
19
|
+
def __getitem__(self, key):
|
20
|
+
row, col = key
|
21
|
+
row, col = str(row), str(col)
|
22
|
+
return self.data.loc[row, col]
|
20
23
|
|
21
|
-
|
22
|
-
|
24
|
+
# 支持 recorder[row, col] = value
|
25
|
+
def __setitem__(self, key, value):
|
26
|
+
row, col = key
|
27
|
+
row, col, value = str(row), str(col), str(value)
|
23
28
|
self.data.loc[row, col] = value
|
24
|
-
|
25
|
-
# 保存
|
26
29
|
self.__save()
|
27
30
|
|
28
|
-
def
|
29
|
-
row, col =
|
30
|
-
|
31
|
-
|
31
|
+
def write(self, row, col, value):
|
32
|
+
self[row, col] = value
|
33
|
+
|
34
|
+
def get(self, row, col):
|
35
|
+
return self[row, col]
|
36
|
+
|
32
37
|
def get_str(self, row, col) -> str:
|
33
|
-
|
34
|
-
result = self.data.loc[row, col]
|
35
|
-
return str(result)
|
38
|
+
return str(self[row, col])
|
36
39
|
|
37
40
|
def get_int(self, row, col) -> int:
|
38
|
-
|
39
|
-
|
40
|
-
return int(result)
|
41
|
+
return int(self[row, col])
|
42
|
+
|
41
43
|
def get_float(self, row, col) -> float:
|
42
|
-
|
43
|
-
|
44
|
-
return float(result)
|
44
|
+
return float(self[row, col])
|
45
|
+
|
45
46
|
def get_bool(self, row, col) -> bool:
|
46
|
-
|
47
|
-
result
|
48
|
-
if result == "True" or result == "true" or result == "1":
|
47
|
+
result = self[row, col]
|
48
|
+
if result in ("True", "true", "1"):
|
49
49
|
return True
|
50
|
-
elif result
|
50
|
+
elif result in ("False", "false", "0"):
|
51
51
|
return False
|
52
52
|
else:
|
53
53
|
raise ValueError(f"无法转换为布尔值 -> {result}")
|
@@ -55,9 +55,7 @@ class B_Record2d:
|
|
55
55
|
def __read(self):
|
56
56
|
try:
|
57
57
|
self.data = pd.read_csv(self.csv_path, index_col=0)
|
58
|
-
except FileNotFoundError:
|
59
|
-
self.data = pd.DataFrame()
|
60
|
-
except pd.errors.EmptyDataError:
|
58
|
+
except (FileNotFoundError, pd.errors.EmptyDataError):
|
61
59
|
self.data = pd.DataFrame()
|
62
60
|
|
63
61
|
def __save(self, csv_path=None):
|
@@ -68,19 +66,20 @@ class B_Record2d:
|
|
68
66
|
def __str__(self):
|
69
67
|
return str(self.data)
|
70
68
|
|
69
|
+
|
71
70
|
if __name__ == '__main__':
|
72
71
|
csv_file = "test_data.csv"
|
73
72
|
|
74
73
|
recorder = B_Record2d(csv_file, mode="w")
|
75
74
|
|
76
|
-
#
|
77
|
-
recorder
|
78
|
-
recorder
|
79
|
-
recorder
|
80
|
-
recorder
|
75
|
+
# 用索引方式赋值
|
76
|
+
recorder["awa", "OvO"] = 10
|
77
|
+
recorder["awa", "TwT"] = 20
|
78
|
+
recorder["qwq", "OvO"] = 30
|
79
|
+
recorder["qwq", "TwT"] = 40
|
81
80
|
|
82
81
|
print("当前内容:")
|
83
82
|
print(recorder)
|
84
83
|
|
85
|
-
|
86
|
-
print(recorder)
|
84
|
+
# 用索引方式读取
|
85
|
+
print("awa, OvO =", recorder["awa", "OvO"])
|
File without changes
|
@@ -0,0 +1,29 @@
|
|
1
|
+
LICENSE
|
2
|
+
README.md
|
3
|
+
setup.py
|
4
|
+
byzh/core/B_os.py
|
5
|
+
byzh/core/__init__.py
|
6
|
+
byzh/core/Barchive/__init__.py
|
7
|
+
byzh/core/Barchive/archive.py
|
8
|
+
byzh/core/Brecorder/__init__.py
|
9
|
+
byzh/core/Brecorder/record1d.py
|
10
|
+
byzh/core/Brecorder/record2d.py
|
11
|
+
byzh/core/Btable/__init__.py
|
12
|
+
byzh/core/Btable/auto_table.py
|
13
|
+
byzh/core/Bterminal/__init__.py
|
14
|
+
byzh/core/Bterminal/cmd.py
|
15
|
+
byzh/core/Bterminal/run_func.py
|
16
|
+
byzh/core/Btqdm/__init__.py
|
17
|
+
byzh/core/Btqdm/my_tqdm.py
|
18
|
+
byzh/core/Butils/__init__.py
|
19
|
+
byzh/core/Butils/decorator.py
|
20
|
+
byzh/core/Butils/text_style.py
|
21
|
+
byzh/core/Butils/timer.py
|
22
|
+
byzh/core/Bwriter/__init__.py
|
23
|
+
byzh/core/Bwriter/writer.py
|
24
|
+
byzh_core.egg-info/PKG-INFO
|
25
|
+
byzh_core.egg-info/SOURCES.txt
|
26
|
+
byzh_core.egg-info/dependency_links.txt
|
27
|
+
byzh_core.egg-info/entry_points.txt
|
28
|
+
byzh_core.egg-info/requires.txt
|
29
|
+
byzh_core.egg-info/top_level.txt
|
@@ -4,7 +4,7 @@ setup(
|
|
4
4
|
name='byzh-core',
|
5
5
|
version=byzh.__version__,
|
6
6
|
author="byzh_rc",
|
7
|
-
description="
|
7
|
+
description="byzh-core是byzh系列的核心库,包含了一些常用的工具函数和类。",
|
8
8
|
long_description=open('README.md').read(),
|
9
9
|
long_description_content_type='text/markdown',
|
10
10
|
license='MIT',
|
@@ -1,328 +0,0 @@
|
|
1
|
-
from ...Butils import B_Color
|
2
|
-
|
3
|
-
|
4
|
-
class B_Config:
|
5
|
-
def __init__(self):
|
6
|
-
super().__init__()
|
7
|
-
self.group_lst = []
|
8
|
-
self.dict_lst = []
|
9
|
-
|
10
|
-
# set-方法
|
11
|
-
def set(self, group, key, value):
|
12
|
-
'''
|
13
|
-
添加元素
|
14
|
-
'''
|
15
|
-
if not isinstance(group, str):
|
16
|
-
raise Exception(f"{B_Color.YELLOW}group({str(group)}) must be str{B_Color.RESET}")
|
17
|
-
if not isinstance(key, str):
|
18
|
-
raise Exception(f"{B_Color.YELLOW}key({str(key)}) must be str{B_Color.RESET}")
|
19
|
-
|
20
|
-
if group not in self.group_lst:
|
21
|
-
self.group_lst.append(group)
|
22
|
-
self.dict_lst.append(dict())
|
23
|
-
|
24
|
-
index = self._get_index(group)
|
25
|
-
self.dict_lst[index][key] = value
|
26
|
-
|
27
|
-
def set_copygroup(self, dst_group, src_group):
|
28
|
-
'''
|
29
|
-
通过复制group来快速添加组
|
30
|
-
'''
|
31
|
-
if not isinstance(dst_group, str):
|
32
|
-
raise Exception(f"{B_Color.YELLOW}group({str(dst_group)}) must be str{B_Color.RESET}")
|
33
|
-
if not isinstance(src_group, str):
|
34
|
-
raise Exception(f"{B_Color.YELLOW}group({str(src_group)}) must be str{B_Color.RESET}")
|
35
|
-
if dst_group in self.group_lst:
|
36
|
-
raise Exception(f"{B_Color.YELLOW}group({str(dst_group)}) already exist{B_Color.RESET}")
|
37
|
-
|
38
|
-
import copy
|
39
|
-
self.group_lst.append(dst_group)
|
40
|
-
self.dict_lst.append(copy.deepcopy(self.dict_lst[self._get_index(src_group)]))
|
41
|
-
|
42
|
-
def set_dictgroup(self, group, dict):
|
43
|
-
'''
|
44
|
-
通过dict来快速添加组
|
45
|
-
'''
|
46
|
-
if group in self.group_lst:
|
47
|
-
raise Exception(f"{B_Color.YELLOW}group({str(group)}) already exist{B_Color.RESET}")
|
48
|
-
self.group_lst.append(group)
|
49
|
-
# 把dict的键值对都化为字符串
|
50
|
-
self.dict_lst.append({str(key): str(value) for key, value in dict.items()})
|
51
|
-
|
52
|
-
# show-方法
|
53
|
-
def show_all(self):
|
54
|
-
'''
|
55
|
-
打印config
|
56
|
-
'''
|
57
|
-
print(f"group_cnt({len(self.group_lst)}) | {self.group_lst} \ndict_cnt:{len(self.dict_lst)}")
|
58
|
-
print()
|
59
|
-
for group, dict in zip(self.group_lst, self.dict_lst):
|
60
|
-
print(f"{group}:\n\t{dict}")
|
61
|
-
|
62
|
-
def show_group(self, group):
|
63
|
-
'''
|
64
|
-
打印某个group
|
65
|
-
'''
|
66
|
-
result = self._get_group_str(group)
|
67
|
-
print(group + ":\n" + result)
|
68
|
-
|
69
|
-
# get-方法
|
70
|
-
def get_str(self, group, key):
|
71
|
-
'''
|
72
|
-
获取某个group的某个key的值
|
73
|
-
'''
|
74
|
-
self._check(group, key)
|
75
|
-
index = self._get_index(group)
|
76
|
-
return str(self.dict_lst[index][key])
|
77
|
-
|
78
|
-
def get_int(self, group, key):
|
79
|
-
'''
|
80
|
-
获取某个group的某个key的值
|
81
|
-
'''
|
82
|
-
self._check(group, key)
|
83
|
-
index = self._get_index(group)
|
84
|
-
return int(self.dict_lst[index][key])
|
85
|
-
|
86
|
-
def get_float(self, group, key):
|
87
|
-
'''
|
88
|
-
获取某个group的某个key的值
|
89
|
-
'''
|
90
|
-
self._check(group, key)
|
91
|
-
index = self._get_index(group)
|
92
|
-
return float(self.dict_lst[index][key])
|
93
|
-
|
94
|
-
def get_bool(self, group, key):
|
95
|
-
'''
|
96
|
-
获取某个group的某个key的值\n
|
97
|
-
只有value为["False", "0", "None"]时,返回False
|
98
|
-
'''
|
99
|
-
self._check(group, key)
|
100
|
-
|
101
|
-
if self.get_str(group, key) in ["False", "0", "None"]:
|
102
|
-
return False
|
103
|
-
elif self.get_str(group, key) in ["True", "1"]:
|
104
|
-
return True
|
105
|
-
else:
|
106
|
-
raise Exception(f"{B_Color.YELLOW}value({str(key)}) cannot change to bool{B_Color.RESET}")
|
107
|
-
|
108
|
-
# save-方法
|
109
|
-
def to_pickle(self, path):
|
110
|
-
'''
|
111
|
-
保存为pickle文件(最稳定的方式)
|
112
|
-
'''
|
113
|
-
import pickle
|
114
|
-
with open(path, 'wb') as f:
|
115
|
-
pickle.dump([self.group_lst, self.dict_lst], f)
|
116
|
-
|
117
|
-
def from_pickle(self, path):
|
118
|
-
'''
|
119
|
-
从pickle文件中读取
|
120
|
-
'''
|
121
|
-
import pickle
|
122
|
-
with open(path, 'rb') as f:
|
123
|
-
[self.group_lst, self.dict_lst] = pickle.load(f)
|
124
|
-
|
125
|
-
def to_json(self, path):
|
126
|
-
'''
|
127
|
-
保存为json文件
|
128
|
-
'''
|
129
|
-
import json
|
130
|
-
with open(path, 'w') as f:
|
131
|
-
for group, group_dict in zip(self.group_lst, self.dict_lst):
|
132
|
-
entry = {"group": group, "dict": group_dict}
|
133
|
-
json.dump(entry, f)
|
134
|
-
f.write("\n")
|
135
|
-
|
136
|
-
def from_json(self, path):
|
137
|
-
'''
|
138
|
-
从json文件中读取
|
139
|
-
'''
|
140
|
-
import json
|
141
|
-
with open(path, 'r') as f:
|
142
|
-
self.group_lst = []
|
143
|
-
self.dict_lst = []
|
144
|
-
for line in f:
|
145
|
-
entry = json.loads(line.strip())
|
146
|
-
self.group_lst.append(entry["group"])
|
147
|
-
self.dict_lst.append(entry["dict"])
|
148
|
-
|
149
|
-
def to_yaml(self, path):
|
150
|
-
'''
|
151
|
-
保存为yaml文件
|
152
|
-
'''
|
153
|
-
import yaml
|
154
|
-
with open(path, 'w') as f:
|
155
|
-
yaml.dump([self.group_lst, self.dict_lst], f)
|
156
|
-
|
157
|
-
def from_yaml(self, path):
|
158
|
-
'''
|
159
|
-
从yaml文件中读取
|
160
|
-
'''
|
161
|
-
import yaml
|
162
|
-
with open(path, 'r') as f:
|
163
|
-
[self.group_lst, self.dict_lst] = yaml.load(f, Loader=yaml.FullLoader)
|
164
|
-
|
165
|
-
def to_ini(self, path):
|
166
|
-
'''
|
167
|
-
保存为ini文件
|
168
|
-
'''
|
169
|
-
with open(path, 'w') as f:
|
170
|
-
for group, dict in zip(self.group_lst, self.dict_lst):
|
171
|
-
f.write(f"[{group}]\n")
|
172
|
-
for key, value in dict.items():
|
173
|
-
f.write(f"{key} = {value}\n")
|
174
|
-
f.write("\n")
|
175
|
-
|
176
|
-
def from_ini(self, path):
|
177
|
-
'''
|
178
|
-
从ini文件中读取
|
179
|
-
'''
|
180
|
-
self.group_lst = []
|
181
|
-
self.dict_lst = []
|
182
|
-
with open(path, 'r') as f:
|
183
|
-
lines = f.readlines()
|
184
|
-
dictionary = dict()
|
185
|
-
for line in lines:
|
186
|
-
line = line.strip()
|
187
|
-
if line.startswith('[') and line.endswith(']'):
|
188
|
-
# 如果字典非空不是dict()
|
189
|
-
if dictionary != dict():
|
190
|
-
self.dict_lst.append(dictionary.copy())
|
191
|
-
dictionary.clear()
|
192
|
-
group = line[1:-1]
|
193
|
-
self.group_lst.append(group)
|
194
|
-
elif line == '':
|
195
|
-
continue
|
196
|
-
else:
|
197
|
-
if '=' in line:
|
198
|
-
key, value = line.split('=', 1)
|
199
|
-
# key和value去除前后空格
|
200
|
-
key = key.strip()
|
201
|
-
value = value.strip()
|
202
|
-
dictionary[key] = value
|
203
|
-
else:
|
204
|
-
dictionary[line] = ''
|
205
|
-
if dictionary != dict():
|
206
|
-
self.dict_lst.append(dictionary.copy())
|
207
|
-
|
208
|
-
def to_csv(self, path):
|
209
|
-
'''
|
210
|
-
保存为csv文件
|
211
|
-
'''
|
212
|
-
import csv
|
213
|
-
with open(path, 'w', newline='') as f:
|
214
|
-
writer = csv.writer(f)
|
215
|
-
|
216
|
-
# Write header: the first row is group names
|
217
|
-
header = ['key'] + self.group_lst
|
218
|
-
writer.writerow(header)
|
219
|
-
|
220
|
-
# Find all unique keys across all groups
|
221
|
-
all_keys = set()
|
222
|
-
for group_dict in self.dict_lst:
|
223
|
-
all_keys.update(group_dict.keys())
|
224
|
-
|
225
|
-
# Write rows for each key
|
226
|
-
for key in all_keys:
|
227
|
-
row = [key]
|
228
|
-
for group_dict in self.dict_lst:
|
229
|
-
row.append(group_dict.get(key, '')) # Add value or empty if key is not present
|
230
|
-
writer.writerow(row)
|
231
|
-
|
232
|
-
def from_csv(self, path):
|
233
|
-
'''
|
234
|
-
从csv文件中读取
|
235
|
-
'''
|
236
|
-
import csv
|
237
|
-
with open(path, 'r') as f:
|
238
|
-
reader = csv.reader(f)
|
239
|
-
|
240
|
-
# Read header: the first row is group names
|
241
|
-
header = next(reader)
|
242
|
-
group_lst = header[1:] # The first column is 'key', rest are groups
|
243
|
-
self.group_lst = group_lst
|
244
|
-
self.dict_lst = [{} for _ in range(len(group_lst))] # Initialize dicts for each group
|
245
|
-
|
246
|
-
# Read the key-value pairs
|
247
|
-
for row in reader:
|
248
|
-
key = row[0]
|
249
|
-
for i, value in enumerate(row[1:], start=0):
|
250
|
-
if value: # Only add value if it's not empty
|
251
|
-
self.dict_lst[i][key] = value
|
252
|
-
|
253
|
-
def to_table(self, path):
|
254
|
-
from ..Btable import B_Table2d
|
255
|
-
my_table = B_Table2d()
|
256
|
-
for index, group in enumerate(self.group_lst):
|
257
|
-
for key, value in self.dict_lst[index].items():
|
258
|
-
my_table[group][key] = value
|
259
|
-
|
260
|
-
my_table.to_txt(path)
|
261
|
-
|
262
|
-
# 工具-方法
|
263
|
-
def __str__(self):
|
264
|
-
result = ""
|
265
|
-
for group in self.group_lst:
|
266
|
-
result += group + ":\n"
|
267
|
-
result += self._get_group_str(group) + "\n"
|
268
|
-
# 去掉最后一个\n
|
269
|
-
result = result[:-1]
|
270
|
-
return result
|
271
|
-
def __getitem__(self, item):
|
272
|
-
return self.dict_lst[item]
|
273
|
-
|
274
|
-
def __setitem__(self, key, value):
|
275
|
-
self.set_dictgroup(key, value)
|
276
|
-
|
277
|
-
def _get_index(self, group):
|
278
|
-
return self.group_lst.index(group)
|
279
|
-
|
280
|
-
def _get_group_str(self, group):
|
281
|
-
self._check(group)
|
282
|
-
index = self._get_index(group)
|
283
|
-
result = "\n".join([f"\t({key} -> {value})" for key, value in self.dict_lst[index].items()])
|
284
|
-
return result
|
285
|
-
|
286
|
-
def _check(self, group, key=None):
|
287
|
-
# 检查group是否是字符串
|
288
|
-
if not isinstance(group, str):
|
289
|
-
raise Exception(f"{B_Color.YELLOW}group({str(group)}) must be str{B_Color.RESET}")
|
290
|
-
# 检查group是否在group_list中
|
291
|
-
if group not in self.group_lst:
|
292
|
-
raise Exception(f"{B_Color.YELLOW}group({str(group)}) not found{B_Color.RESET}")
|
293
|
-
|
294
|
-
if key is not None:
|
295
|
-
# 检查key是否是字符串
|
296
|
-
if not isinstance(key, str):
|
297
|
-
raise Exception(f"{B_Color.YELLOW}key({str(key)}) must be str{B_Color.RESET}")
|
298
|
-
# 检查key是否在dict中
|
299
|
-
index = self._get_index(group)
|
300
|
-
if key not in self.dict_lst[index]:
|
301
|
-
raise Exception(f"{B_Color.YELLOW}key({str(key)}) not found{B_Color.RESET}")
|
302
|
-
|
303
|
-
|
304
|
-
if __name__ == '__main__':
|
305
|
-
a = B_Config()
|
306
|
-
|
307
|
-
a.set('awa', 'a', 'None')
|
308
|
-
a.set('awa', 'b', '123')
|
309
|
-
a.set('awa', '345', '33333')
|
310
|
-
|
311
|
-
a.set('awa', 'a532', 'No32ne')
|
312
|
-
a.set('awa', 'b13', '123412')
|
313
|
-
a.set('awa', '321345', '33342333')
|
314
|
-
|
315
|
-
a.set_copygroup('default', 'qwq')
|
316
|
-
a.set('qwq', '345', 'aaaaaa')
|
317
|
-
|
318
|
-
a.to_csv('config.csv')
|
319
|
-
a.from_csv('config.csv')
|
320
|
-
# a.to_yaml('config.yaml')
|
321
|
-
# a.from_yaml('config.yaml')
|
322
|
-
# a.to_pickle('config.pkl')
|
323
|
-
# a.from_pickle('config.pkl')
|
324
|
-
# a.to_json('config.json')
|
325
|
-
# a.from_json('config.json')
|
326
|
-
|
327
|
-
print(a.get_str('awa', 'b13'))
|
328
|
-
print(a)
|