- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmagic.py
More file actions
Latest commit
95 lines (83 loc) · 3.39 KB
/
Copy pathmagic.py
File metadata and controls
95 lines (83 loc) · 3.39 KB
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
90
91
92
93
94
95
"""
# Python实用函数
# 包含函数:
print_with_style() ----- 拓展print()函数,使其输出时可以携带样式
print_spend_time()装饰器 ----- 获取某函数执行时所消耗的时间
"""
fromfunctoolsimportwraps
fromdatetimeimportdatetime
defprint_with_style(*args, style='', **kwargs):
"""带样式的打印,它是对print()函数的拓展.
# 参数:
style:要使用的样式,它可以是以下值:(多个样式之间用加号'+'隔开)
'r':红色
'g':绿色
'b':蓝色
'B':加粗
'U':下划线
其它: 其它格式控制代码,如:'\033[7m'
others:指其它可用于print()函数的参数,如end, sep, file等.
# 例子:
print_with_style(value, ..., style='g+B')
print_with_style(value, ..., style='B+\033[7m', sep='>')
"""
styles= {
'r': '\033[31m', # 红色
'g': '\033[92m', # 绿色
'b': '\033[94m', # 蓝色
'B': '\033[1m', # 加粗
'U': '\033[4m'# 下划线
}
style_lsit=set(style.split('+'))
forsinstyle_lsit:
ifsinstyles:
print(styles[s], end='')
elifs.startswith('\033'):
print(s, end='')
print(*args, **kwargs)
print('\033[0m', end='')
defprint_spend_time(format_str='执行函数{func_name},共耗时:{d}天{h}小时{m}分钟{s:02d}秒{ms}微秒', end='\n'):
"""获取函数执行时间的装饰器,可对输出字符串进行定制.
# 参数:
format_str: 定制的输出字符串,可在其中使用的插槽有:
{d}: 天,
{h}:小时,
{m}:分钟,
{s}:秒,
{ms}:微秒,
{th}:总小时,
{tm}:总分钟,
{ts}:总秒,
{tms}:带微秒的总秒,
{func_name}:执行的函数名
end: 换行符,默认为'\\n'
# 例子:
@print_spend_time(format_str='执行完成,共耗时:{tms} s')
def f():
...
"""
defdecorator(func):
@wraps(func)
defwrapper(*args, **kwargs):
start_time=datetime.now()
result=func(*args, **kwargs) # 执行被包装的函数
end_time=datetime.now()
spend_time=end_time-start_time
m, s=divmod(spend_time.seconds, 60) # seconds
h, m=divmod(m, 60) # hours, minutes
d=spend_time.days# days
ms=spend_time.microseconds# microseconds
th=d*24+h# total hours
tm=d*24*60+h*60+m# total minutes
ts=d*24*60*60+spend_time.seconds# total seconds
tms=ts+spend_time.microseconds# total seconds with microseconds
final_str=format_str.format(d=d, h=h,
m=m, s=s,
ms=ms, th=th,
tm=tm, ts=ts,
tms=tms,
func_name=func.__name__+'()')
print(final_str, end=end)
returnresult
returnwrapper
returndecorator