dc-cmnutils 0.0.3__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.
- dc/cmnutils/basicdata/convert.py +192 -0
- dc/cmnutils/basicdata/convert_basic.py +393 -0
- dc/cmnutils/basicdata/data.py +588 -0
- dc/cmnutils/basicdata/json.py +94 -0
- dc/cmnutils/basicdata/object.py +814 -0
- dc/cmnutils/collection/collection.py +757 -0
- dc/cmnutils/database/database_access.py +213 -0
- dc/cmnutils/database/database_accessor.py +287 -0
- dc/cmnutils/database/db_operater.py +283 -0
- dc/cmnutils/database/dbutil.py +389 -0
- dc/cmnutils/io/file/cfg/config.py +262 -0
- dc/cmnutils/io/file/file.py +212 -0
- dc/cmnutils/io/file/file_utils.py +605 -0
- dc/cmnutils/io/log/log.py +43 -0
- dc/cmnutils/io/log/log_utils.py +50 -0
- dc/cmnutils/net/email.py +185 -0
- dc/cmnutils/net/http.py +468 -0
- dc/cmnutils/net/net.py +252 -0
- dc/cmnutils/sys/env/linuxenv.py +384 -0
- dc/cmnutils/sys/env/windowsenv.py +235 -0
- dc/cmnutils/sys/envutil.py +442 -0
- dc/cmnutils/sys/processutil.py +447 -0
- dc/cmnutils/sys/sys.py +640 -0
- dc/cmnutils/sys/sys_utils.py +580 -0
- dc/cmnutils/sys/threadutil.py +315 -0
- dc_cmnutils-0.0.3.dist-info/METADATA +34 -0
- dc_cmnutils-0.0.3.dist-info/RECORD +30 -0
- dc_cmnutils-0.0.3.dist-info/WHEEL +5 -0
- dc_cmnutils-0.0.3.dist-info/licenses/LICENSE.TXT +19 -0
- dc_cmnutils-0.0.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
import configparser
|
|
4
|
+
import xml.etree.ElementTree as ET
|
|
5
|
+
from typing import Any, Dict, Optional, Union
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ConfigUtil:
|
|
9
|
+
"""配置文件工具类,支持ini、json、xml等多种格式的配置文件读写操作"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, file_path: str):
|
|
12
|
+
"""
|
|
13
|
+
初始化ConfigUtil
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
file_path: 配置文件路径
|
|
17
|
+
"""
|
|
18
|
+
self.file_path = file_path
|
|
19
|
+
self.config_type = self._detect_config_type()
|
|
20
|
+
|
|
21
|
+
def _detect_config_type(self) -> str:
|
|
22
|
+
"""
|
|
23
|
+
根据文件扩展名检测配置文件类型
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
str: 配置文件类型 (ini, json, xml)
|
|
27
|
+
"""
|
|
28
|
+
ext = os.path.splitext(self.file_path)[1].lower()
|
|
29
|
+
if ext == '.ini':
|
|
30
|
+
return 'ini'
|
|
31
|
+
elif ext == '.json':
|
|
32
|
+
return 'json'
|
|
33
|
+
elif ext in ['.xml', '.config']:
|
|
34
|
+
return 'xml'
|
|
35
|
+
else:
|
|
36
|
+
raise ValueError(f"Unsupported config file type: {ext}")
|
|
37
|
+
|
|
38
|
+
def read(self, section: Optional[str] = None, key: Optional[str] = None) -> Any:
|
|
39
|
+
"""
|
|
40
|
+
读取配置文件
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
section: 分区/节点名称 (对于ini/xml)
|
|
44
|
+
key: 键名
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
配置值或整个配置字典
|
|
48
|
+
"""
|
|
49
|
+
if self.config_type == 'ini':
|
|
50
|
+
return self._read_ini(section, key)
|
|
51
|
+
elif self.config_type == 'json':
|
|
52
|
+
return self._read_json(key)
|
|
53
|
+
elif self.config_type == 'xml':
|
|
54
|
+
return self._read_xml(section, key)
|
|
55
|
+
|
|
56
|
+
def write(self, data: Any, section: Optional[str] = None, key: Optional[str] = None) -> bool:
|
|
57
|
+
"""
|
|
58
|
+
写入配置文件
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
data: 要写入的数据
|
|
62
|
+
section: 分区/节点名称 (对于ini/xml)
|
|
63
|
+
key: 键名
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
bool: 是否成功写入
|
|
67
|
+
"""
|
|
68
|
+
try:
|
|
69
|
+
if self.config_type == 'ini':
|
|
70
|
+
return self._write_ini(data, section, key)
|
|
71
|
+
elif self.config_type == 'json':
|
|
72
|
+
return self._write_json(data, key)
|
|
73
|
+
elif self.config_type == 'xml':
|
|
74
|
+
return self._write_xml(data, section, key)
|
|
75
|
+
return False
|
|
76
|
+
except Exception as e:
|
|
77
|
+
print(f"Error writing config: {e}")
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
def _read_ini(self, section: Optional[str] = None, key: Optional[str] = None) -> Any:
|
|
81
|
+
"""读取INI配置文件"""
|
|
82
|
+
config = configparser.ConfigParser()
|
|
83
|
+
config.read(self.file_path, encoding='utf-8')
|
|
84
|
+
|
|
85
|
+
if not section and not key:
|
|
86
|
+
# 返回所有配置
|
|
87
|
+
return {s: dict(config.items(s)) for s in config.sections()}
|
|
88
|
+
elif section and not key:
|
|
89
|
+
# 返回指定section的所有配置
|
|
90
|
+
if config.has_section(section):
|
|
91
|
+
return dict(config.items(section))
|
|
92
|
+
return None
|
|
93
|
+
elif section and key:
|
|
94
|
+
# 返回指定section和key的配置值
|
|
95
|
+
if config.has_section(section) and config.has_option(section, key):
|
|
96
|
+
return config.get(section, key)
|
|
97
|
+
return None
|
|
98
|
+
else:
|
|
99
|
+
raise ValueError("Section must be specified when reading a key from INI file")
|
|
100
|
+
|
|
101
|
+
def _write_ini(self, data: Any, section: Optional[str] = None, key: Optional[str] = None) -> bool:
|
|
102
|
+
"""写入INI配置文件"""
|
|
103
|
+
config = configparser.ConfigParser()
|
|
104
|
+
|
|
105
|
+
# 如果文件已存在,先读取现有内容
|
|
106
|
+
if os.path.exists(self.file_path):
|
|
107
|
+
config.read(self.file_path, encoding='utf-8')
|
|
108
|
+
|
|
109
|
+
if isinstance(data, dict) and not section and not key:
|
|
110
|
+
# 写入整个配置字典
|
|
111
|
+
for sec, options in data.items():
|
|
112
|
+
if not config.has_section(sec):
|
|
113
|
+
config.add_section(sec)
|
|
114
|
+
for k, v in options.items():
|
|
115
|
+
config.set(sec, k, str(v))
|
|
116
|
+
elif section and isinstance(data, dict) and not key:
|
|
117
|
+
# 写入整个section
|
|
118
|
+
if not config.has_section(section):
|
|
119
|
+
config.add_section(section)
|
|
120
|
+
for k, v in data.items():
|
|
121
|
+
config.set(section, k, str(v))
|
|
122
|
+
elif section and key:
|
|
123
|
+
# 写入单个键值
|
|
124
|
+
if not config.has_section(section):
|
|
125
|
+
config.add_section(section)
|
|
126
|
+
config.set(section, key, str(data))
|
|
127
|
+
else:
|
|
128
|
+
raise ValueError("Invalid parameters for INI file writing")
|
|
129
|
+
|
|
130
|
+
# 写入文件
|
|
131
|
+
with open(self.file_path, 'w', encoding='utf-8') as f:
|
|
132
|
+
config.write(f)
|
|
133
|
+
|
|
134
|
+
return True
|
|
135
|
+
|
|
136
|
+
def _read_json(self, key: Optional[str] = None) -> Any:
|
|
137
|
+
"""读取JSON配置文件"""
|
|
138
|
+
if not os.path.exists(self.file_path):
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
with open(self.file_path, 'r', encoding='utf-8') as f:
|
|
142
|
+
data = json.load(f)
|
|
143
|
+
|
|
144
|
+
if key:
|
|
145
|
+
return data.get(key) if isinstance(data, dict) else None
|
|
146
|
+
return data
|
|
147
|
+
|
|
148
|
+
def _write_json(self, data: Any, key: Optional[str] = None) -> bool:
|
|
149
|
+
"""写入JSON配置文件"""
|
|
150
|
+
# 如果文件已存在,先读取现有内容
|
|
151
|
+
existing_data = {}
|
|
152
|
+
if os.path.exists(self.file_path):
|
|
153
|
+
with open(self.file_path, 'r', encoding='utf-8') as f:
|
|
154
|
+
try:
|
|
155
|
+
existing_data = json.load(f)
|
|
156
|
+
except json.JSONDecodeError:
|
|
157
|
+
existing_data = {}
|
|
158
|
+
|
|
159
|
+
if key:
|
|
160
|
+
# 只更新指定键的值
|
|
161
|
+
if not isinstance(existing_data, dict):
|
|
162
|
+
existing_data = {}
|
|
163
|
+
existing_data[key] = data
|
|
164
|
+
data_to_write = existing_data
|
|
165
|
+
else:
|
|
166
|
+
# 替换整个文件内容
|
|
167
|
+
data_to_write = data
|
|
168
|
+
|
|
169
|
+
# 写入文件
|
|
170
|
+
with open(self.file_path, 'w', encoding='utf-8') as f:
|
|
171
|
+
json.dump(data_to_write, f, indent=4, ensure_ascii=False)
|
|
172
|
+
|
|
173
|
+
return True
|
|
174
|
+
|
|
175
|
+
def _read_xml(self, section: Optional[str] = None, key: Optional[str] = None) -> Any:
|
|
176
|
+
"""读取XML配置文件"""
|
|
177
|
+
if not os.path.exists(self.file_path):
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
tree = ET.parse(self.file_path)
|
|
181
|
+
root = tree.getroot()
|
|
182
|
+
|
|
183
|
+
if not section and not key:
|
|
184
|
+
# 返回整个XML结构
|
|
185
|
+
return self._xml_to_dict(root)
|
|
186
|
+
elif section and not key:
|
|
187
|
+
# 返回指定节点的所有子节点
|
|
188
|
+
element = root.find(section)
|
|
189
|
+
return self._xml_to_dict(element) if element is not None else None
|
|
190
|
+
elif section and key:
|
|
191
|
+
# 返回指定节点和键的值
|
|
192
|
+
element = root.find(section)
|
|
193
|
+
if element is not None:
|
|
194
|
+
sub_element = element.find(key)
|
|
195
|
+
return sub_element.text if sub_element is not None else None
|
|
196
|
+
return None
|
|
197
|
+
else:
|
|
198
|
+
raise ValueError("Section must be specified when reading a key from XML file")
|
|
199
|
+
|
|
200
|
+
def _write_xml(self, data: Any, section: Optional[str] = None, key: Optional[str] = None) -> bool:
|
|
201
|
+
"""写入XML配置文件"""
|
|
202
|
+
# 如果文件已存在,先读取现有内容
|
|
203
|
+
if os.path.exists(self.file_path):
|
|
204
|
+
tree = ET.parse(self.file_path)
|
|
205
|
+
root = tree.getroot()
|
|
206
|
+
else:
|
|
207
|
+
root = ET.Element("config")
|
|
208
|
+
tree = ET.ElementTree(root)
|
|
209
|
+
|
|
210
|
+
if isinstance(data, dict) and not section and not key:
|
|
211
|
+
# 写入整个配置字典
|
|
212
|
+
for sec, options in data.items():
|
|
213
|
+
section_element = root.find(sec)
|
|
214
|
+
if section_element is None:
|
|
215
|
+
section_element = ET.SubElement(root, sec)
|
|
216
|
+
|
|
217
|
+
for k, v in options.items():
|
|
218
|
+
element = section_element.find(k)
|
|
219
|
+
if element is None:
|
|
220
|
+
element = ET.SubElement(section_element, k)
|
|
221
|
+
element.text = str(v)
|
|
222
|
+
elif section and isinstance(data, dict) and not key:
|
|
223
|
+
# 写入整个section
|
|
224
|
+
section_element = root.find(section)
|
|
225
|
+
if section_element is None:
|
|
226
|
+
section_element = ET.SubElement(root, section)
|
|
227
|
+
|
|
228
|
+
for k, v in data.items():
|
|
229
|
+
element = section_element.find(k)
|
|
230
|
+
if element is None:
|
|
231
|
+
element = ET.SubElement(section_element, k)
|
|
232
|
+
element.text = str(v)
|
|
233
|
+
elif section and key:
|
|
234
|
+
# 写入单个键值
|
|
235
|
+
section_element = root.find(section)
|
|
236
|
+
if section_element is None:
|
|
237
|
+
section_element = ET.SubElement(root, section)
|
|
238
|
+
|
|
239
|
+
element = section_element.find(key)
|
|
240
|
+
if element is None:
|
|
241
|
+
element = ET.SubElement(section_element, key)
|
|
242
|
+
element.text = str(data)
|
|
243
|
+
else:
|
|
244
|
+
raise ValueError("Invalid parameters for XML file writing")
|
|
245
|
+
|
|
246
|
+
# 写入文件
|
|
247
|
+
tree.write(self.file_path, encoding='utf-8', xml_declaration=True)
|
|
248
|
+
return True
|
|
249
|
+
|
|
250
|
+
def _xml_to_dict(self, element: Optional[ET.Element]) -> Any:
|
|
251
|
+
"""将XML元素转换为字典"""
|
|
252
|
+
if element is None:
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
result = {}
|
|
256
|
+
for child in element:
|
|
257
|
+
if len(child) == 0:
|
|
258
|
+
result[child.tag] = child.text
|
|
259
|
+
else:
|
|
260
|
+
result[child.tag] = self._xml_to_dict(child)
|
|
261
|
+
return result
|
|
262
|
+
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
sys.path.append("../..")
|
|
4
|
+
from tests.definitions.result import Result
|
|
5
|
+
import shutil
|
|
6
|
+
from typing import Optional
|
|
7
|
+
from dc.cmnlib.io.file.file import FileHelper
|
|
8
|
+
|
|
9
|
+
class FileUtil(FileHelper):
|
|
10
|
+
"""文件操作工具类,封装常见读写逻辑"""
|
|
11
|
+
|
|
12
|
+
@staticmethod
|
|
13
|
+
def read_text(file_path: str, encoding: str = 'utf-8') -> Result[str]:
|
|
14
|
+
"""读取文本文件内容"""
|
|
15
|
+
try:
|
|
16
|
+
with open(file_path, 'r', encoding=encoding) as f:
|
|
17
|
+
result=Result.success_instance("",f.read())
|
|
18
|
+
#except FileNotFoundError:
|
|
19
|
+
# result=Result.failure_instance("",f"File {file_path} not found.")
|
|
20
|
+
# raise FileNotFoundError(f"文件不存在: {file_path}")
|
|
21
|
+
except Exception as e:
|
|
22
|
+
result=Result.error_instance(str(e))
|
|
23
|
+
# raise IOError(f"读取文件失败: {e}")
|
|
24
|
+
return result
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def write_text(file_path: str, content: str, encoding: str = 'utf-8', mode: str = 'w') -> Result:
|
|
28
|
+
"""写入文本文件(默认覆盖模式)"""
|
|
29
|
+
try:
|
|
30
|
+
with open(file_path, mode, encoding=encoding) as f:
|
|
31
|
+
f.write(content)
|
|
32
|
+
result=Result.success_instance("")
|
|
33
|
+
except Exception as e:
|
|
34
|
+
result=Result.error_instance(str(e))
|
|
35
|
+
# raise IOError(f"写入文件失败: {e}")
|
|
36
|
+
return result
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def append_line(file_path: str, line: str, encoding: str = 'utf-8') -> Result:
|
|
43
|
+
"""追加单行文本到文件末尾"""
|
|
44
|
+
return FileUtil.write_text(file_path, line + '\n', encoding, mode='a')
|
|
45
|
+
|
|
46
|
+
@staticmethod
|
|
47
|
+
def exists(file_path: str) -> bool:
|
|
48
|
+
"""检查文件是否存在"""
|
|
49
|
+
return os.path.exists(file_path)
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def create_if_not_exists(dir_path: str) -> None:
|
|
53
|
+
"""如果目录不存在则创建"""
|
|
54
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def file_exists(path: str) -> bool:
|
|
58
|
+
"""
|
|
59
|
+
检查文件是否存在
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
path (str): 文件路径
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
bool: 是否存在
|
|
66
|
+
"""
|
|
67
|
+
return os.path.isfile(path)
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def dir_exists(path: str) -> bool:
|
|
71
|
+
"""
|
|
72
|
+
检查目录是否存在
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
path (str): 目录路径
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
bool: 是否存在
|
|
79
|
+
"""
|
|
80
|
+
return os.path.isdir(path)
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def create_dir(path: str, parents: bool = True, exist_ok: bool = True) -> bool:
|
|
84
|
+
"""
|
|
85
|
+
创建目录
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
path (str): 目录路径
|
|
89
|
+
parents (bool): 是否创建父目录
|
|
90
|
+
exist_ok (bool): 目录已存在时是否忽略
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
bool: 是否创建成功
|
|
94
|
+
"""
|
|
95
|
+
try:
|
|
96
|
+
os.makedirs(path, exist_ok=exist_ok)
|
|
97
|
+
return True
|
|
98
|
+
except OSError:
|
|
99
|
+
return False
|
|
100
|
+
|
|
101
|
+
@staticmethod
|
|
102
|
+
def remove_file(path: str) -> bool:
|
|
103
|
+
"""
|
|
104
|
+
删除文件
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
path (str): 文件路径
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
bool: 是否删除成功
|
|
111
|
+
"""
|
|
112
|
+
try:
|
|
113
|
+
os.remove(path)
|
|
114
|
+
return True
|
|
115
|
+
except OSError:
|
|
116
|
+
return False
|
|
117
|
+
|
|
118
|
+
@staticmethod
|
|
119
|
+
def remove_dir(path: str, recursive: bool = True) -> bool:
|
|
120
|
+
"""
|
|
121
|
+
删除目录
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
path (str): 目录路径
|
|
125
|
+
recursive (bool): 是否递归删除
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
bool: 是否删除成功
|
|
129
|
+
"""
|
|
130
|
+
try:
|
|
131
|
+
# if recursive:
|
|
132
|
+
# shutil.rmtree(path)
|
|
133
|
+
# else:
|
|
134
|
+
os.rmdir(path)
|
|
135
|
+
return True
|
|
136
|
+
except OSError:
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
@staticmethod
|
|
140
|
+
def copy_file(src: str, dst: str, overwrite: bool = True) -> bool:
|
|
141
|
+
"""
|
|
142
|
+
复制文件
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
src (str): 源文件路径
|
|
146
|
+
dst (str): 目标文件路径
|
|
147
|
+
overwrite (bool): 是否覆盖已存在的文件
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
bool: 是否复制成功
|
|
151
|
+
"""
|
|
152
|
+
if not overwrite and os.path.exists(dst):
|
|
153
|
+
return False
|
|
154
|
+
try:
|
|
155
|
+
|
|
156
|
+
shutil.copy2(src, dst)
|
|
157
|
+
return True
|
|
158
|
+
except OSError:
|
|
159
|
+
return False
|
|
160
|
+
|
|
161
|
+
@staticmethod
|
|
162
|
+
def move_file(src: str, dst: str, overwrite: bool = True) -> bool:
|
|
163
|
+
"""
|
|
164
|
+
移动/重命名文件
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
src (str): 源文件路径
|
|
168
|
+
dst (str): 目标文件路径
|
|
169
|
+
overwrite (bool): 是否覆盖已存在的文件
|
|
170
|
+
|
|
171
|
+
Returns:
|
|
172
|
+
bool: 是否移动成功
|
|
173
|
+
"""
|
|
174
|
+
if not overwrite and os.path.exists(dst):
|
|
175
|
+
return False
|
|
176
|
+
try:
|
|
177
|
+
shutil.move(src, dst)
|
|
178
|
+
return True
|
|
179
|
+
except OSError:
|
|
180
|
+
return False
|
|
181
|
+
|
|
182
|
+
@staticmethod
|
|
183
|
+
def get_file_size(path: str) -> Optional[int]:
|
|
184
|
+
"""
|
|
185
|
+
获取文件大小(字节)
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
path (str): 文件路径
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
Optional[int]: 文件大小(字节),文件不存在返回None
|
|
192
|
+
"""
|
|
193
|
+
try:
|
|
194
|
+
return os.path.getsize(path)
|
|
195
|
+
except OSError:
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
@staticmethod
|
|
199
|
+
def get_file_modify_time(path: str) -> Optional[float]:
|
|
200
|
+
"""
|
|
201
|
+
获取文件修改时间(时间戳)
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
path (str): 文件路径
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
Optional[float]: 修改时间戳,文件不存在返回None
|
|
208
|
+
"""
|
|
209
|
+
try:
|
|
210
|
+
return os.path.getmtime(path)
|
|
211
|
+
except OSError:
|
|
212
|
+
return None
|