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,605 @@
|
|
|
1
|
+
"""文件操作帮助类
|
|
2
|
+
|
|
3
|
+
提供文件读写、目录操作等常用功能封装。
|
|
4
|
+
所有方法均为静态方法,使用线程锁保证线程安全,适用于多线程环境。
|
|
5
|
+
"""
|
|
6
|
+
import fnmatch
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import json
|
|
10
|
+
import csv
|
|
11
|
+
import configparser
|
|
12
|
+
from typing import Any, List, Dict, Optional, Tuple
|
|
13
|
+
import threading
|
|
14
|
+
from file import FileUtil
|
|
15
|
+
|
|
16
|
+
class FileUtils(FileUtil):
|
|
17
|
+
"""文件操作帮助类"""
|
|
18
|
+
|
|
19
|
+
_lock = threading.Lock()
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def read_text(file_path: str, encoding: str = 'utf-8', errors: str = 'replace') -> str:
|
|
23
|
+
"""读取文本文件
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
file_path: 文件路径
|
|
27
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
28
|
+
errors: 错误处理方式,默认为 'replace'
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
str: 文件内容
|
|
32
|
+
"""
|
|
33
|
+
if not file_path or not isinstance(file_path, str):
|
|
34
|
+
return ""
|
|
35
|
+
with FileUtils._lock:
|
|
36
|
+
try:
|
|
37
|
+
with open(file_path, 'r', encoding=encoding, errors=errors) as f:
|
|
38
|
+
return f.read()
|
|
39
|
+
except (IOError, OSError):
|
|
40
|
+
return ""
|
|
41
|
+
|
|
42
|
+
@staticmethod
|
|
43
|
+
def write_text(file_path: str, content: str, encoding: str = 'utf-8', errors: str = 'replace', mode: str = 'w') -> bool:
|
|
44
|
+
"""写入文本文件
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
file_path: 文件路径
|
|
48
|
+
content: 要写入的内容
|
|
49
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
50
|
+
errors: 错误处理方式,默认为 'replace'
|
|
51
|
+
mode: 写入模式,'w' 覆盖写入,'a' 追加写入,默认为 'w'
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
bool: 是否写入成功
|
|
55
|
+
"""
|
|
56
|
+
if not file_path or not isinstance(file_path, str):
|
|
57
|
+
return False
|
|
58
|
+
with FileUtils._lock:
|
|
59
|
+
try:
|
|
60
|
+
FileUtils.ensure_dir_exists(os.path.dirname(file_path))
|
|
61
|
+
with open(file_path, mode, encoding=encoding, errors=errors) as f:
|
|
62
|
+
f.write(content)
|
|
63
|
+
return True
|
|
64
|
+
except (IOError, OSError):
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def read_lines(file_path: str, encoding: str = 'utf-8', errors: str = 'replace', skip_empty: bool = True) -> List[str]:
|
|
69
|
+
"""按行读取文本文件
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
file_path: 文件路径
|
|
73
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
74
|
+
errors: 错误处理方式,默认为 'replace'
|
|
75
|
+
skip_empty: 是否跳过空行,默认为 True
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
List[str]: 行内容列表
|
|
79
|
+
"""
|
|
80
|
+
if not file_path or not isinstance(file_path, str):
|
|
81
|
+
return []
|
|
82
|
+
with FileUtils._lock:
|
|
83
|
+
try:
|
|
84
|
+
with open(file_path, 'r', encoding=encoding, errors=errors) as f:
|
|
85
|
+
lines = f.readlines()
|
|
86
|
+
if skip_empty:
|
|
87
|
+
return [line.rstrip('\n\r') for line in lines if line.strip()]
|
|
88
|
+
return [line.rstrip('\n\r') for line in lines]
|
|
89
|
+
except (IOError, OSError):
|
|
90
|
+
return []
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
def write_lines(file_path: str, lines: List[str], encoding: str = 'utf-8', errors: str = 'replace', mode: str = 'w') -> bool:
|
|
94
|
+
"""按行写入文本文件
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
file_path: 文件路径
|
|
98
|
+
lines: 行内容列表
|
|
99
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
100
|
+
errors: 错误处理方式,默认为 'replace'
|
|
101
|
+
mode: 写入模式,'w' 覆盖写入,'a' 追加写入,默认为 'w'
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
bool: 是否写入成功
|
|
105
|
+
"""
|
|
106
|
+
if not file_path or not isinstance(file_path, str) or not lines:
|
|
107
|
+
return False
|
|
108
|
+
with FileUtils._lock:
|
|
109
|
+
try:
|
|
110
|
+
FileUtils.ensure_dir_exists(os.path.dirname(file_path))
|
|
111
|
+
with open(file_path, mode, encoding=encoding, errors=errors) as f:
|
|
112
|
+
f.write('\n'.join(lines) + '\n')
|
|
113
|
+
return True
|
|
114
|
+
except (IOError, OSError):
|
|
115
|
+
return False
|
|
116
|
+
|
|
117
|
+
@staticmethod
|
|
118
|
+
def read_binary(file_path: str) -> bytes:
|
|
119
|
+
"""读取二进制文件
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
file_path: 文件路径
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
bytes: 文件内容
|
|
126
|
+
"""
|
|
127
|
+
if not file_path or not isinstance(file_path, str):
|
|
128
|
+
return b""
|
|
129
|
+
with FileUtils._lock:
|
|
130
|
+
try:
|
|
131
|
+
with open(file_path, 'rb') as f:
|
|
132
|
+
return f.read()
|
|
133
|
+
except (IOError, OSError):
|
|
134
|
+
return b""
|
|
135
|
+
|
|
136
|
+
@staticmethod
|
|
137
|
+
def write_binary(file_path: str, content: bytes, mode: str = 'wb') -> bool:
|
|
138
|
+
"""写入二进制文件
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
file_path: 文件路径
|
|
142
|
+
content: 要写入的内容
|
|
143
|
+
mode: 写入模式,'wb' 覆盖写入,'ab' 追加写入,默认为 'wb'
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
bool: 是否写入成功
|
|
147
|
+
"""
|
|
148
|
+
if not file_path or not isinstance(file_path, str) or content is None:
|
|
149
|
+
return False
|
|
150
|
+
with FileUtils._lock:
|
|
151
|
+
try:
|
|
152
|
+
FileUtils.ensure_dir_exists(os.path.dirname(file_path))
|
|
153
|
+
with open(file_path, mode) as f:
|
|
154
|
+
f.write(content)
|
|
155
|
+
return True
|
|
156
|
+
except (IOError, OSError):
|
|
157
|
+
return False
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def read_json(file_path: str, encoding: str = 'utf-8') -> Dict[str, Any]:
|
|
161
|
+
"""读取 JSON 文件
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
file_path: 文件路径
|
|
165
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
Dict[str, Any]: JSON 数据
|
|
169
|
+
"""
|
|
170
|
+
if not file_path or not isinstance(file_path, str):
|
|
171
|
+
return {}
|
|
172
|
+
with FileUtils._lock:
|
|
173
|
+
try:
|
|
174
|
+
with open(file_path, 'r', encoding=encoding) as f:
|
|
175
|
+
return json.load(f)
|
|
176
|
+
except (IOError, OSError, json.JSONDecodeError):
|
|
177
|
+
return {}
|
|
178
|
+
|
|
179
|
+
@staticmethod
|
|
180
|
+
def write_json(file_path: str, data: Dict[str, Any], encoding: str = 'utf-8', indent: int = 2) -> bool:
|
|
181
|
+
"""写入 JSON 文件
|
|
182
|
+
|
|
183
|
+
Args:
|
|
184
|
+
file_path: 文件路径
|
|
185
|
+
data: 要写入的数据
|
|
186
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
187
|
+
indent: 缩进空格数,默认为 2
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
bool: 是否写入成功
|
|
191
|
+
"""
|
|
192
|
+
if not file_path or not isinstance(file_path, str) or not data:
|
|
193
|
+
return False
|
|
194
|
+
with FileUtils._lock:
|
|
195
|
+
try:
|
|
196
|
+
FileUtils.ensure_dir_exists(os.path.dirname(file_path))
|
|
197
|
+
with open(file_path, 'w', encoding=encoding) as f:
|
|
198
|
+
json.dump(data, f, indent=indent, ensure_ascii=False)
|
|
199
|
+
return True
|
|
200
|
+
except (IOError, OSError, TypeError):
|
|
201
|
+
return False
|
|
202
|
+
|
|
203
|
+
@staticmethod
|
|
204
|
+
def read_csv(file_path: str, encoding: str = 'utf-8', delimiter: str = ',') -> List[Dict[str, Any]]:
|
|
205
|
+
"""读取 CSV 文件
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
file_path: 文件路径
|
|
209
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
210
|
+
delimiter: 分隔符,默认为逗号
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
List[Dict[str, Any]]: CSV 数据列表
|
|
214
|
+
"""
|
|
215
|
+
if not file_path or not isinstance(file_path, str):
|
|
216
|
+
return []
|
|
217
|
+
with FileUtils._lock:
|
|
218
|
+
try:
|
|
219
|
+
with open(file_path, 'r', encoding=encoding) as f:
|
|
220
|
+
reader = csv.DictReader(f, delimiter=delimiter)
|
|
221
|
+
return list(reader)
|
|
222
|
+
except (IOError, OSError):
|
|
223
|
+
return []
|
|
224
|
+
|
|
225
|
+
@staticmethod
|
|
226
|
+
def write_csv(file_path: str, data: List[Dict[str, Any]], encoding: str = 'utf-8', delimiter: str = ',') -> bool:
|
|
227
|
+
"""写入 CSV 文件
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
file_path: 文件路径
|
|
231
|
+
data: 要写入的数据
|
|
232
|
+
encoding: 编码方式,默认为 'utf-8'
|
|
233
|
+
delimiter: 分隔符,默认为逗号
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
bool: 是否写入成功
|
|
237
|
+
"""
|
|
238
|
+
if not file_path or not isinstance(file_path, str) or not data:
|
|
239
|
+
return False
|
|
240
|
+
with FileUtils._lock:
|
|
241
|
+
try:
|
|
242
|
+
FileUtils.ensure_dir_exists(os.path.dirname(file_path))
|
|
243
|
+
with open(file_path, 'w', encoding=encoding, newline='') as f:
|
|
244
|
+
if data:
|
|
245
|
+
fieldnames = data[0].keys()
|
|
246
|
+
writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter=delimiter)
|
|
247
|
+
writer.writeheader()
|
|
248
|
+
writer.writerows(data)
|
|
249
|
+
return True
|
|
250
|
+
except (IOError, OSError, TypeError):
|
|
251
|
+
return False
|
|
252
|
+
|
|
253
|
+
@staticmethod
|
|
254
|
+
def read_config(file_path: str) -> configparser.ConfigParser:
|
|
255
|
+
"""读取配置文件
|
|
256
|
+
|
|
257
|
+
Args:
|
|
258
|
+
file_path: 文件路径
|
|
259
|
+
|
|
260
|
+
Returns:
|
|
261
|
+
configparser.ConfigParser: 配置对象
|
|
262
|
+
"""
|
|
263
|
+
config = configparser.ConfigParser()
|
|
264
|
+
if not file_path or not isinstance(file_path, str):
|
|
265
|
+
return config
|
|
266
|
+
with FileUtils._lock:
|
|
267
|
+
try:
|
|
268
|
+
config.read(file_path, encoding='utf-8')
|
|
269
|
+
except (IOError, OSError):
|
|
270
|
+
pass
|
|
271
|
+
return config
|
|
272
|
+
|
|
273
|
+
@staticmethod
|
|
274
|
+
def write_config(file_path: str, config: configparser.ConfigParser) -> bool:
|
|
275
|
+
"""写入配置文件
|
|
276
|
+
|
|
277
|
+
Args:
|
|
278
|
+
file_path: 文件路径
|
|
279
|
+
config: 配置对象
|
|
280
|
+
|
|
281
|
+
Returns:
|
|
282
|
+
bool: 是否写入成功
|
|
283
|
+
"""
|
|
284
|
+
if not file_path or not isinstance(file_path, str) or not config:
|
|
285
|
+
return False
|
|
286
|
+
with FileUtils._lock:
|
|
287
|
+
try:
|
|
288
|
+
FileUtils.ensure_dir_exists(os.path.dirname(file_path))
|
|
289
|
+
with open(file_path, 'w', encoding='utf-8') as f:
|
|
290
|
+
config.write(f)
|
|
291
|
+
return True
|
|
292
|
+
except (IOError, OSError, TypeError):
|
|
293
|
+
return False
|
|
294
|
+
|
|
295
|
+
@staticmethod
|
|
296
|
+
def exists(file_path: str) -> bool:
|
|
297
|
+
"""检查文件或目录是否存在
|
|
298
|
+
|
|
299
|
+
Args:
|
|
300
|
+
file_path: 文件或目录路径
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
bool: 是否存在
|
|
304
|
+
"""
|
|
305
|
+
if not file_path or not isinstance(file_path, str):
|
|
306
|
+
return False
|
|
307
|
+
return os.path.exists(file_path)
|
|
308
|
+
|
|
309
|
+
@staticmethod
|
|
310
|
+
def is_file(file_path: str) -> bool:
|
|
311
|
+
"""检查路径是否为文件
|
|
312
|
+
|
|
313
|
+
Args:
|
|
314
|
+
file_path: 文件路径
|
|
315
|
+
|
|
316
|
+
Returns:
|
|
317
|
+
bool: 是否为文件
|
|
318
|
+
"""
|
|
319
|
+
if not file_path or not isinstance(file_path, str):
|
|
320
|
+
return False
|
|
321
|
+
return os.path.isfile(file_path)
|
|
322
|
+
|
|
323
|
+
@staticmethod
|
|
324
|
+
def is_dir(dir_path: str) -> bool:
|
|
325
|
+
"""检查路径是否为目录
|
|
326
|
+
|
|
327
|
+
Args:
|
|
328
|
+
dir_path: 目录路径
|
|
329
|
+
|
|
330
|
+
Returns:
|
|
331
|
+
bool: 是否为目录
|
|
332
|
+
"""
|
|
333
|
+
if not dir_path or not isinstance(dir_path, str):
|
|
334
|
+
return False
|
|
335
|
+
return os.path.isdir(dir_path)
|
|
336
|
+
|
|
337
|
+
@staticmethod
|
|
338
|
+
def ensure_dir_exists(dir_path: str) -> bool:
|
|
339
|
+
"""确保目录存在,如果不存在则创建
|
|
340
|
+
|
|
341
|
+
Args:
|
|
342
|
+
dir_path: 目录路径
|
|
343
|
+
|
|
344
|
+
Returns:
|
|
345
|
+
bool: 是否创建成功或目录已存在
|
|
346
|
+
"""
|
|
347
|
+
if not dir_path or not isinstance(dir_path, str):
|
|
348
|
+
return False
|
|
349
|
+
with FileUtils._lock:
|
|
350
|
+
try:
|
|
351
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
352
|
+
return True
|
|
353
|
+
except (IOError, OSError):
|
|
354
|
+
return False
|
|
355
|
+
|
|
356
|
+
@staticmethod
|
|
357
|
+
def create_dir(dir_path: str) -> bool:
|
|
358
|
+
"""创建目录
|
|
359
|
+
|
|
360
|
+
Args:
|
|
361
|
+
dir_path: 目录路径
|
|
362
|
+
|
|
363
|
+
Returns:
|
|
364
|
+
bool: 是否创建成功
|
|
365
|
+
"""
|
|
366
|
+
if not dir_path or not isinstance(dir_path, str):
|
|
367
|
+
return False
|
|
368
|
+
with FileUtils._lock:
|
|
369
|
+
try:
|
|
370
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
371
|
+
return True
|
|
372
|
+
except (IOError, OSError):
|
|
373
|
+
return False
|
|
374
|
+
|
|
375
|
+
@staticmethod
|
|
376
|
+
def delete_file(file_path: str) -> bool:
|
|
377
|
+
"""删除文件
|
|
378
|
+
|
|
379
|
+
Args:
|
|
380
|
+
file_path: 文件路径
|
|
381
|
+
|
|
382
|
+
Returns:
|
|
383
|
+
bool: 是否删除成功
|
|
384
|
+
"""
|
|
385
|
+
if not file_path or not isinstance(file_path, str):
|
|
386
|
+
return False
|
|
387
|
+
with FileUtils._lock:
|
|
388
|
+
try:
|
|
389
|
+
if os.path.isfile(file_path):
|
|
390
|
+
os.remove(file_path)
|
|
391
|
+
return True
|
|
392
|
+
return False
|
|
393
|
+
except (IOError, OSError):
|
|
394
|
+
return False
|
|
395
|
+
|
|
396
|
+
@staticmethod
|
|
397
|
+
def delete_dir(dir_path: str, recursive: bool = False) -> bool:
|
|
398
|
+
"""删除目录
|
|
399
|
+
|
|
400
|
+
Args:
|
|
401
|
+
dir_path: 目录路径
|
|
402
|
+
recursive: 是否递归删除,默认为 False
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
bool: 是否删除成功
|
|
406
|
+
"""
|
|
407
|
+
if not dir_path or not isinstance(dir_path, str):
|
|
408
|
+
return False
|
|
409
|
+
with FileUtils._lock:
|
|
410
|
+
try:
|
|
411
|
+
if os.path.isdir(dir_path):
|
|
412
|
+
if recursive:
|
|
413
|
+
shutil.rmtree(dir_path)
|
|
414
|
+
else:
|
|
415
|
+
os.rmdir(dir_path)
|
|
416
|
+
return True
|
|
417
|
+
return False
|
|
418
|
+
except (IOError, OSError):
|
|
419
|
+
return False
|
|
420
|
+
|
|
421
|
+
@staticmethod
|
|
422
|
+
def copy_file(source: str, destination: str, overwrite: bool = True) -> bool:
|
|
423
|
+
"""复制文件
|
|
424
|
+
|
|
425
|
+
Args:
|
|
426
|
+
source: 源文件路径
|
|
427
|
+
destination: 目标文件路径
|
|
428
|
+
overwrite: 是否覆盖已存在的文件,默认为 True
|
|
429
|
+
|
|
430
|
+
Returns:
|
|
431
|
+
bool: 是否复制成功
|
|
432
|
+
"""
|
|
433
|
+
if not source or not destination:
|
|
434
|
+
return False
|
|
435
|
+
with FileUtils._lock:
|
|
436
|
+
try:
|
|
437
|
+
if overwrite or not os.path.exists(destination):
|
|
438
|
+
FileUtils.ensure_dir_exists(os.path.dirname(destination))
|
|
439
|
+
shutil.copy2(source, destination)
|
|
440
|
+
return True
|
|
441
|
+
return False
|
|
442
|
+
except (IOError, OSError):
|
|
443
|
+
return False
|
|
444
|
+
|
|
445
|
+
@staticmethod
|
|
446
|
+
def move_file(source: str, destination: str, overwrite: bool = True) -> bool:
|
|
447
|
+
"""移动文件
|
|
448
|
+
|
|
449
|
+
Args:
|
|
450
|
+
source: 源文件路径
|
|
451
|
+
destination: 目标文件路径
|
|
452
|
+
overwrite: 是否覆盖已存在的文件,默认为 True
|
|
453
|
+
|
|
454
|
+
Returns:
|
|
455
|
+
bool: 是否移动成功
|
|
456
|
+
"""
|
|
457
|
+
if not source or not destination:
|
|
458
|
+
return False
|
|
459
|
+
with FileUtils._lock:
|
|
460
|
+
try:
|
|
461
|
+
if overwrite and os.path.exists(destination):
|
|
462
|
+
os.remove(destination)
|
|
463
|
+
FileUtils.ensure_dir_exists(os.path.dirname(destination))
|
|
464
|
+
shutil.move(source, destination)
|
|
465
|
+
return True
|
|
466
|
+
except (IOError, OSError):
|
|
467
|
+
return False
|
|
468
|
+
|
|
469
|
+
@staticmethod
|
|
470
|
+
def get_file_size(file_path: str) -> int:
|
|
471
|
+
"""获取文件大小(字节)
|
|
472
|
+
|
|
473
|
+
Args:
|
|
474
|
+
file_path: 文件路径
|
|
475
|
+
|
|
476
|
+
Returns:
|
|
477
|
+
int: 文件大小,失败返回 0
|
|
478
|
+
"""
|
|
479
|
+
if not file_path or not isinstance(file_path, str):
|
|
480
|
+
return 0
|
|
481
|
+
try:
|
|
482
|
+
return os.path.getsize(file_path)
|
|
483
|
+
except (IOError, OSError):
|
|
484
|
+
return 0
|
|
485
|
+
|
|
486
|
+
@staticmethod
|
|
487
|
+
def get_file_info(file_path: str) -> Dict[str, Any]:
|
|
488
|
+
"""获取文件信息
|
|
489
|
+
|
|
490
|
+
Args:
|
|
491
|
+
file_path: 文件路径
|
|
492
|
+
|
|
493
|
+
Returns:
|
|
494
|
+
Dict[str, Any]: 文件信息字典
|
|
495
|
+
"""
|
|
496
|
+
if not file_path or not isinstance(file_path, str):
|
|
497
|
+
return {}
|
|
498
|
+
try:
|
|
499
|
+
stat = os.stat(file_path)
|
|
500
|
+
return {
|
|
501
|
+
'name': os.path.basename(file_path),
|
|
502
|
+
'path': os.path.abspath(file_path),
|
|
503
|
+
'size': stat.st_size,
|
|
504
|
+
'mtime': stat.st_mtime,
|
|
505
|
+
'ctime': stat.st_ctime,
|
|
506
|
+
'is_file': os.path.isfile(file_path),
|
|
507
|
+
'is_dir': os.path.isdir(file_path)
|
|
508
|
+
}
|
|
509
|
+
except (IOError, OSError):
|
|
510
|
+
return {}
|
|
511
|
+
|
|
512
|
+
@staticmethod
|
|
513
|
+
def list_files(dir_path: str, pattern: str = None) -> List[str]:
|
|
514
|
+
"""列出目录中的文件
|
|
515
|
+
|
|
516
|
+
Args:
|
|
517
|
+
dir_path: 目录路径
|
|
518
|
+
pattern: 文件匹配模式,支持通配符
|
|
519
|
+
|
|
520
|
+
Returns:
|
|
521
|
+
List[str]: 文件路径列表
|
|
522
|
+
"""
|
|
523
|
+
if not dir_path or not isinstance(dir_path, str):
|
|
524
|
+
return []
|
|
525
|
+
try:
|
|
526
|
+
files = []
|
|
527
|
+
for entry in os.listdir(dir_path):
|
|
528
|
+
full_path = os.path.join(dir_path, entry)
|
|
529
|
+
if os.path.isfile(full_path):
|
|
530
|
+
if pattern:
|
|
531
|
+
if fnmatch.fnmatch(entry, pattern):
|
|
532
|
+
files.append(full_path)
|
|
533
|
+
else:
|
|
534
|
+
files.append(full_path)
|
|
535
|
+
return files
|
|
536
|
+
except (IOError, OSError):
|
|
537
|
+
return []
|
|
538
|
+
|
|
539
|
+
@staticmethod
|
|
540
|
+
def list_dirs(dir_path: str) -> List[str]:
|
|
541
|
+
"""列出目录中的子目录
|
|
542
|
+
|
|
543
|
+
Args:
|
|
544
|
+
dir_path: 目录路径
|
|
545
|
+
|
|
546
|
+
Returns:
|
|
547
|
+
List[str]: 子目录路径列表
|
|
548
|
+
"""
|
|
549
|
+
if not dir_path or not isinstance(dir_path, str):
|
|
550
|
+
return []
|
|
551
|
+
try:
|
|
552
|
+
dirs = []
|
|
553
|
+
for entry in os.listdir(dir_path):
|
|
554
|
+
full_path = os.path.join(dir_path, entry)
|
|
555
|
+
if os.path.isdir(full_path):
|
|
556
|
+
dirs.append(full_path)
|
|
557
|
+
return dirs
|
|
558
|
+
except (IOError, OSError):
|
|
559
|
+
return []
|
|
560
|
+
|
|
561
|
+
@staticmethod
|
|
562
|
+
def get_extension(file_path: str) -> str:
|
|
563
|
+
"""获取文件扩展名
|
|
564
|
+
|
|
565
|
+
Args:
|
|
566
|
+
file_path: 文件路径
|
|
567
|
+
|
|
568
|
+
Returns:
|
|
569
|
+
str: 文件扩展名(包含点号)
|
|
570
|
+
"""
|
|
571
|
+
if not file_path or not isinstance(file_path, str):
|
|
572
|
+
return ""
|
|
573
|
+
return os.path.splitext(file_path)[1]
|
|
574
|
+
|
|
575
|
+
@staticmethod
|
|
576
|
+
def get_file_name(file_path: str, include_extension: bool = True) -> str:
|
|
577
|
+
"""获取文件名
|
|
578
|
+
|
|
579
|
+
Args:
|
|
580
|
+
file_path: 文件路径
|
|
581
|
+
include_extension: 是否包含扩展名,默认为 True
|
|
582
|
+
|
|
583
|
+
Returns:
|
|
584
|
+
str: 文件名
|
|
585
|
+
"""
|
|
586
|
+
if not file_path or not isinstance(file_path, str):
|
|
587
|
+
return ""
|
|
588
|
+
name = os.path.basename(file_path)
|
|
589
|
+
if not include_extension:
|
|
590
|
+
name = os.path.splitext(name)[0]
|
|
591
|
+
return name
|
|
592
|
+
|
|
593
|
+
@staticmethod
|
|
594
|
+
def get_parent_dir(file_path: str) -> str:
|
|
595
|
+
"""获取父目录路径
|
|
596
|
+
|
|
597
|
+
Args:
|
|
598
|
+
file_path: 文件路径
|
|
599
|
+
|
|
600
|
+
Returns:
|
|
601
|
+
str: 父目录路径
|
|
602
|
+
"""
|
|
603
|
+
if not file_path or not isinstance(file_path, str):
|
|
604
|
+
return ""
|
|
605
|
+
return os.path.dirname(file_path)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import logging.config
|
|
3
|
+
import inspect
|
|
4
|
+
|
|
5
|
+
class Log(object):
|
|
6
|
+
logging.config.fileConfig('/etc/logging.conf')
|
|
7
|
+
__logger = logging.getLogger('script')
|
|
8
|
+
|
|
9
|
+
@classmethod
|
|
10
|
+
def set_level(cls, level):
|
|
11
|
+
cls.__logger.setLevel(level)
|
|
12
|
+
|
|
13
|
+
@classmethod
|
|
14
|
+
def debug(cls, msg, *args, **kwargs):
|
|
15
|
+
cls._log(logging.DEBUG, msg, *args, **kwargs)
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def info(cls, msg, *args, **kwargs):
|
|
19
|
+
cls._log(logging.INFO, msg, *args, **kwargs)
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def warning(cls, msg, *args, **kwargs):
|
|
23
|
+
cls._log(logging.WARNING, msg, *args, **kwargs)
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def error(cls, msg, *args, **kwargs):
|
|
27
|
+
cls._log(logging.ERROR, msg, *args, **kwargs)
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def critical(cls, msg, *args, **kwargs):
|
|
31
|
+
cls._log(logging.CRITICAL, msg, *args, **kwargs)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def _log(cls, level, msg, *args, **kwargs):
|
|
35
|
+
# 获取调用者的信息
|
|
36
|
+
frame = inspect.currentframe().f_back.f_back
|
|
37
|
+
caller = inspect.getframeinfo(frame)
|
|
38
|
+
# 记录日志,传入调用者的文件名和行号
|
|
39
|
+
cls.__logger.log(level, msg, *args, **kwargs, extra={'filename': caller.filename, 'lineno': caller.lineno})
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def get_logger(cls):
|
|
43
|
+
return cls.__logger
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
import time
|
|
4
|
+
import logging
|
|
5
|
+
#from .singleton import Singleton
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
#@Singleton # 如需打印不同路径的日志(运行日志、审计日志),则不能使用单例模式(注释或删除此行)。此外,还需设定参数name。
|
|
9
|
+
class Logger:
|
|
10
|
+
def __init__(self, set_level="INFO",
|
|
11
|
+
name=os.path.split(os.path.splitext(sys.argv[0])[0])[-1],
|
|
12
|
+
log_name=time.strftime("%Y-%m-%d.log", time.localtime()),
|
|
13
|
+
log_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), ""),
|
|
14
|
+
use_console=True):
|
|
15
|
+
"""
|
|
16
|
+
:param set_level: 日志级别["NOTSET"|"DEBUG"|"INFO"|"WARNING"|"ERROR"|"CRITICAL"],默认为INFO
|
|
17
|
+
:param name: 日志中打印的name,默认为运行程序的name
|
|
18
|
+
:param log_name: 日志文件的名字,默认为当前时间(年-月-日.log)
|
|
19
|
+
:param log_path: 日志文件夹的路径,默认为logger.py同级目录中的log文件夹
|
|
20
|
+
:param use_console: 是否在控制台打印,默认为True
|
|
21
|
+
"""
|
|
22
|
+
if not set_level:
|
|
23
|
+
set_level = self._exec_type() # 设置set_level为None,自动获取当前运行模式
|
|
24
|
+
self.__logger = logging.getLogger(name)
|
|
25
|
+
self.setLevel(
|
|
26
|
+
getattr(logging, set_level.upper()) if hasattr(logging, set_level.upper()) else logging.INFO) # 设置日志级别
|
|
27
|
+
if not os.path.exists(log_path): # 创建日志目录
|
|
28
|
+
os.makedirs(log_path)
|
|
29
|
+
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s")
|
|
30
|
+
handler_list = list()
|
|
31
|
+
handler_list.append(logging.FileHandler(os.path.join(log_path, log_name), encoding="utf-8"))
|
|
32
|
+
if use_console:
|
|
33
|
+
handler_list.append(logging.StreamHandler())
|
|
34
|
+
for handler in handler_list:
|
|
35
|
+
handler.setFormatter(formatter)
|
|
36
|
+
self.addHandler(handler)
|
|
37
|
+
|
|
38
|
+
def __getattr__(self, item):
|
|
39
|
+
return getattr(self.logger, item)
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def logger(self):
|
|
43
|
+
return self.__logger
|
|
44
|
+
|
|
45
|
+
@logger.setter
|
|
46
|
+
def logger(self, func):
|
|
47
|
+
self.__logger = func
|
|
48
|
+
|
|
49
|
+
def _exec_type(self):
|
|
50
|
+
return "DEBUG" if os.environ.get("IPYTHONENABLE") else "INFO"
|