-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.py
76 lines (66 loc) · 1.96 KB
/
tools.py
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
# -*- coding: utf-8 -*-
"""
@author: zx013
"""
import random
#限制随机,防止S/L,S/L时需存取__staticrandom
__random = random._inst.random
__staticrandom = []
def staticrandom(number=0):
for i in range(number):
__staticrandom.append(__random())
def new_random():
r = __random()
__staticrandom.append(r)
return __staticrandom.pop(0)
random.random = random._inst.random = new_random
#异常时返回默认值
def except_default(default=None):
def run_func(func):
def run(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as ex:
print(func.__name__, ex)
return default
run.__name__ = func.__name__
return run
return run_func
#死循环的处理
class LoopException(Exception):
retry = 1000
def loop_retry(func):
def run(*args, **kwargs):
for i in range(3):
try:
return func(*args, **kwargs)
except LoopException:
print('retry :', func.__name__)
run.__name__ = func.__name__
return run
class Tools:
#从目录中选出一个值
@staticmethod
def dict_choice(dictionary):
total = sum(dictionary.values())
if total < 1:
return
rand = random.randint(1, total)
for key, val in dictionary.items():
rand -= val
if rand <= 0:
return key
#迭代当前值和上一个值
@staticmethod
def iter_previous(iterator):
previous = None
for number, element in enumerate(iterator):
if number > 0:
yield previous, element
previous = element
#将参数变成list
@staticmethod
def object_list(ob):
if not isinstance(ob, tuple) and not isinstance(ob, list):
ob = [ob]
return ob