我写的常用工具函数
# json文件读写
python中的字典可以直接保存为json文件,也可以读取python文件load之后变成字典对象
如果字典中字符串含有中文,在调用json.dum时,会默认被保存成\u开头的编码,此时需要在参数中加上ensure_ascii=False
。读取的时候不用管,直接读就是正常的。indent = 4
表示json保存的时候格式化,缩进为4个空格。
# tools.py
import logging, coloredlogs
from functools import wraps
import json
# 使用: from tools import config, saveConfig, logger, printExcept
# config.json文件
with open('config.json','r',encoding='utf-8') as f:
config = json.load(f)
def saveConfig(confDict):
with open('config.json', 'w',encoding='utf-8') as f:
json.dump(confDict, f, ensure_ascii=False, indent=4)
# 多次尝试执行某个函数,
# 该函数返回bool类型,True表示成功。False表示失败
# 多次尝试,执行成功立刻返回Ture,重试多次都失败则返回False
def tryExecTimes(func, times:int, *args, **kwargs)->bool:
for i in range(times):
ret = func(*args, **kwargs)
if ret:
return True
return False
# color logging
class _logger:
def __init__(self):
coloredlogs.DEFAULT_FIELD_STYLES = \
{'asctime': {'color': 'green'},
'hostname': {'color': 'magenta'},
'levelname': {'color': 'black', 'bold': True},
'module': {'color': 'blue'},
'name': {'color': 'blue'},
'programname': {'color': 'cyan'}
}
coloredlogs.DEFAULT_LEVEL_STYLES = \
{'critical': {'bold': True, 'background':'red'},
'debug': {'color': 'green'},
'error': {'color': 'red'},
'info': {},
'notice': {'color': 'magenta'},
'spam': {'color': 'green', 'faint': True},
'success': {'color': 'green', 'bold': True},
'verbose': {'color': 'blue'},
'warning': {'color': 'yellow'}
}
self.logger = logging.getLogger('main')
# coloredlogs.install(level='INFO', fmt='%(asctime)s,%(msecs)03d %(levelname)s %(message)s') 不要删
coloredlogs.install(level='INFO', fmt='%(asctime)s, %(levelname)s, %(module)s[%(lineno)d] %(message)s')
# Some examples.
# logger.debug("this is a debugging message")
# logger.info("this is an informational message")
# logger.warning("this is a warning message")
# logger.error("this is an error message")
# logger.critical("this is a critical message")
logger = _logger().logger
# wrap一段代码,如果有异常则打印异常信息,然后继续运行。
def printExcept(func):
@wraps(func)
def inner(*args, **kwargs):
try:
ret = func(*args, **kwargs)
return ret
except Exception as e:
print("func '{}' error: {}".format(func.__name__, str(e)))
return inner
def wrapperTpl(func):
@wraps(func)
def inner(*args, **kwargs):
'''在执行目标函数之前要执行的内容'''
ret = func(*args, **kwargs)
'''在执行目标函数之后要执行的内容'''
return ret
return inner
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
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
编辑 (opens new window)
上次更新: 2021/10/11, 12:43:58