Skip to content

Commit 1e5698c

Browse files
authored
Merge pull request ictar#17 from lujun9972/20160610
两篇翻译
2 parents c880be7 + 2f3e1d1 commit 1e5698c

2 files changed

Lines changed: 312 additions & 0 deletions

File tree

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
#+TITLE: 如何创建记录异常日志的装饰器
2+
#+URL: http://www.blog.pythonlibrary.org/2016/06/09/python-how-to-create-an-exception-logging-decorator/
3+
#+AUTHOR: lujun9972
4+
#+CATEGORY: Python Common
5+
#+DATE: [2016-06-10 五 15:41]
6+
#+OPTIONS: ^:{}
7+
8+
有一天,我突然想要创建一个用于捕获并记录异常的装饰器. 我在[[https://gist.github.com/diosmosis/1148066][Github]] 上发现一个颇为复杂的例子,该例子启发了我,并让我写下了以下代码:
9+
#+BEGIN_SRC python
10+
# exception_decor.py
11+
import logging
12+
13+
def create_logger():
14+
"""
15+
Creates a logging object and returns it
16+
"""
17+
logger = logging.getLogger("example_logger")
18+
logger.setLevel(logging.INFO)
19+
# create the logging file handler
20+
fh = logging.FileHandler("/path/to/test.log")
21+
fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
22+
formatter = logging.Formatter(fmt)
23+
fh.setFormatter(formatter)
24+
# add handler to logger object
25+
logger.addHandler(fh)
26+
return logger
27+
28+
def exception(function):
29+
"""
30+
A decorator that wraps the passed in function and logs
31+
exceptions should one occur
32+
"""
33+
def wrapper(*args, **kwargs):
34+
logger = create_logger()
35+
try:
36+
return function(*args, **kwargs)
37+
except:
38+
# log the exception
39+
err = "There was an exception in "
40+
err += function.__name__
41+
logger.exception(err)
42+
# re-raise the exception
43+
raise
44+
return wrapper
45+
#+END_SRC
46+
47+
在这段代码中,定义了两个函数. 第一个函数创建并返回了一个logging对象. 第二个函数为我们的装饰器函数,其中我们将传入的函数包裹进一个try/except中,并使用logger记录下任何产生的异常. 同时你还会发现,我还记录下了产生异常的函数名.
48+
49+
现在让我们测试一下这个装饰器. 创建一个新Python脚本并添加以下代码. 请确保这个新Python脚本与上面创建装饰器的脚本在同一个目录下.
50+
#+BEGIN_SRC python
51+
from exception_decor import exception
52+
53+
@exception
54+
def zero_divide():
55+
1 / 0
56+
57+
if __name__ == '__main__':
58+
zero_divide()
59+
#+END_SRC
60+
61+
当你在命令行中运行该代码后,你会发现多出了一个日志文件,其内容为:
62+
#+BEGIN_EXAMPLE
63+
2016-06-09 08:26:50,874 - example_logger - ERROR - There was an exception in zero_divide
64+
Traceback (most recent call last):
65+
File "/home/mike/exception_decor.py", line 29, in wrapper
66+
return function(*args, **kwargs)
67+
File "/home/mike/test_exceptions.py", line 5, in zero_divide
68+
1 / 0
69+
ZeroDivisionError: integer division or modulo by zero
70+
#+END_EXAMPLE
71+
72+
我觉得这份代码很方便,我希望你们大家也会觉得有用.
73+
74+
UPDATE: 一个热心的读者提出,将代码泛化成从外界传递一个logger对象到装饰器会更好些. 那么然我们来看看如何实现它!
75+
76+
* 传递logger到我们的装饰器中
77+
首先,将原始的代码中的logging代码拆到自己的模块中。 假设放到文件exception_logger.py中. 下面是源代码:
78+
#+BEGIN_SRC python
79+
# exception_logger.py
80+
import logging
81+
def create_logger():
82+
"""
83+
Creates a logging object and returns it
84+
"""
85+
logger = logging.getLogger("example_logger")
86+
logger.setLevel(logging.INFO)
87+
# create the logging file handler
88+
fh = logging.FileHandler(r"/path/to/test.log")
89+
fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
90+
formatter = logging.Formatter(fmt)
91+
fh.setFormatter(formatter)
92+
# add handler to logger object
93+
logger.addHandler(fh)
94+
return logger
95+
logger = create_logger()
96+
#+END_SRC
97+
98+
然后我们修改装饰器代码,使之接受一个logger为参数并保存为exception_decor.py
99+
#+BEGIN_SRC python
100+
# exception_decor.py
101+
102+
import functools
103+
104+
105+
def exception(logger):
106+
"""
107+
A decorator that wraps the passed in function and logs
108+
exceptions should one occur
109+
110+
@param logger: The logging object
111+
"""
112+
113+
def decorator(func):
114+
115+
def wrapper(*args, **kwargs):
116+
try:
117+
return func(*args, **kwargs)
118+
except:
119+
# log the exception
120+
err = "There was an exception in "
121+
err += func.__name__
122+
logger.exception(err)
123+
124+
# re-raise the exception
125+
raise
126+
return wrapper
127+
return decorator
128+
#+END_SRC
129+
130+
你会发现我们定义了多层嵌套的函数。 请看仔细并理解其中的意思。 最后,我们需要修改一下测试的代码:
131+
#+BEGIN_SRC python
132+
from exception_decor import exception
133+
from exception_logger import logger
134+
135+
@exception(logger)
136+
def zero_divide():
137+
1 / 0
138+
139+
if __name__ == '__main__':
140+
zero_divide()
141+
#+END_SRC
142+
143+
代码中,我们导入了装饰器和logger对象。 然后我们将装饰器作用于要记录的函数,并且我们给该装饰器传递了一个logger对象。 你运行该测试代码后,会发现产生了与第一个测试相同的文件.
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
#+TITLE: 随机性的多种用途
2+
#+URL: http://jugad2.blogspot.jp/2016/06/the-many-uses-of-randomness.html
3+
#+AUTHOR: lujun9972
4+
#+CATEGORY: Python Common
5+
#+DATE: [2016-06-10 五 14:42]
6+
#+OPTIONS: ^:{}
7+
8+
[[https://en.wikipedia.org/wiki/Random_number_generation][计算机随机数生成器 ]](RNGs)[fn:1] 有很多用途. 最近在教授一次程序课时,我演示了随机数的一种用法,本来我觉得这是很普遍的一种用法,结果居然有一位参与者对这种用法表示很惊奇. 这件事情使得我意识到,对于许多初学者,甚至有些富有经验的程序员来说,恐怕对于随机数的很多用法都不是很熟悉.
9+
10+
因此我想到了写这篇博客, 这里我会演示随机数的一些用法. 这里的例子使用的是python语言,但是其原理和概念也可以被借用于其他编程语言--只要它也能产生随机数.
11+
12+
注意: 所有关于随机数的使用方法,都无需用到什么高深的数学知识.
13+
14+
让我们开始吧.
15+
16+
首先,从Python标准库中导入并查看一下随机模块包含了哪些内容
17+
#+BEGIN_SRC python
18+
import random
19+
dir(random)
20+
#+END_SRC
21+
22+
#+RESULTS:
23+
:
24+
: ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
25+
26+
我们可以看到,该模块中包含了许多函数以及包括重要数学常量(例如_e为数学常量e,_pi为数学常量pi. 这两个常量也可以在math模块中找到,分别为math.e和math.pi)在内的其他属性.
27+
28+
在本篇博文中,我需要展示的是random()函数的一些使用方法. 该函数是random模块中最基础的几个函数之一. 也许在以后的博文中,我还会接着演示其他函数及其在其他领域的使用方式.
29+
30+
让我们来输出一下random函数的文档说明字符串:
31+
#+BEGIN_SRC python
32+
print random.random.__doc__
33+
#+END_SRC
34+
35+
#+RESULTS:
36+
: random() -> x in the interval [0, 1).
37+
38+
可以看到,该函数返回一个处于半闭区间[0,1)的随机浮点数, 即随机的一个x,满足0.0<=x<1.0
39+
40+
下面是一个名为fn_random.py的程序,演示了random()函数的一些用法:
41+
#+BEGIN_SRC python :session "none"
42+
from __future__ import print_function
43+
44+
# fn_random.py
45+
# A program showing various uses of the "random" function
46+
# from the "random" module of Python's standard library.
47+
# Author: Vasudev Ram - https://vasudevram.github.io
48+
# Copyright 2016 Vasudev Ram
49+
50+
from random import random
51+
from random import getstate, setstate
52+
53+
print("Ex. 1. Plain calls to random():")
54+
print("Gives 10 random float values in the interval [0, 1).")
55+
for i in range(10):
56+
print(random())
57+
58+
print()
59+
60+
print("Ex. 2. Calls to random() scaled by 10:")
61+
print("Gives 10 random float values in the interval [0, 10).")
62+
for i in range(10):
63+
print(10.0 * random())
64+
65+
print()
66+
67+
print("Ex. 3. Calls to random() scaled by 10 and offset by -5:")
68+
print("Gives 10 random float values in the interval [-5, 5).")
69+
for i in range(10):
70+
print(10.0 * random() - 5.0)
71+
72+
print()
73+
74+
print("Ex. 4. Calls to random() scaled by 20 and offset by 40:")
75+
print("Gives 10 random float values in the interval [40, 60).")
76+
for i in range(10):
77+
print(20.0 * random() + 40.0)
78+
#+END_SRC
79+
80+
下面是该程序的运行输出:
81+
#+BEGIN_EXAMPLE
82+
python fn_random.py
83+
84+
Ex. 1. Plain calls to random():
85+
Gives 10 random float values in the interval [0, 1).
86+
0.978618769308
87+
0.429672807728
88+
0.807873374428
89+
0.00775248310523
90+
0.367435959496
91+
0.452718276649
92+
0.15952248582
93+
0.183989787263
94+
0.240112681717
95+
0.873556193781
96+
97+
Ex. 2. Calls to random() scaled by 10:
98+
Gives 10 random float values in the interval [0, 10).
99+
8.66851830984
100+
8.06203422551
101+
6.68791916223
102+
6.83023335837
103+
2.28298961244
104+
5.06491614858
105+
9.27404238781
106+
2.30473573581
107+
7.62983863372
108+
7.18179372151
109+
110+
Ex. 3. Calls to random() scaled by 10 and offset by -5:
111+
Gives 10 random float values in the interval [-5, 5).
112+
4.28960887925
113+
-1.48913007202
114+
-0.534170376124
115+
3.36741617894
116+
-3.50802287142
117+
1.46218930484
118+
-3.37237288568
119+
-2.49675571636
120+
-3.56593768859
121+
-1.49924682779
122+
123+
Ex. 4. Calls to random() scaled by 20 and offset by 40:
124+
Gives 10 random float values in the interval [40, 60).
125+
56.4292882009
126+
40.888150119
127+
56.867782498
128+
58.3162130934
129+
41.642982556
130+
40.8419833357
131+
52.3684662857
132+
45.3000297458
133+
43.1515262997
134+
52.1129658036
135+
#+END_EXAMPLE
136+
137+
上面的程序演示了如何通过乘法和加法将random()返回的原本处于0到1之间的值,转换为其他区间的值.
138+
139+
注意上面程序中4个部分输出的值都是完全不一样的,即使将乘法和加法的运算因素算在内也是完全不同的. 例如,第二个部分输出的值并不都是第一个部分输出值的10倍--虽然从代码上看,第二部分与第一部分唯一不同点就在于乘以了一个10.
140+
产生这个结果的原因是因为,随机数是通过遍历一个很长的序列来产生的,即序列前10个值作为第一部分代码的输出,而后10个值作为第二部分代码的输出.
141+
142+
若我们希望四个部分所产生的随机数一样怎么办呢(不算上乘法与加法造成的差异)?例如在有些科学与统计实验中,需要不断重复同一样的数据. 一个很直观的办法就是将第一次产生的随机数保持下来,然后在之后的代码中使用保存下来的这些随机数.
143+
144+
但是通过模块中的getstate()和setstate()函数,我们也能实现这一点.
145+
146+
首先将这一行放在Ex.1的代码前.
147+
#+BEGIN_SRC python
148+
state = random.getstate()
149+
#+END_SRC
150+
151+
然后将下行放在Ex.2到Ex.4的代码前.
152+
Then put this line:
153+
#+BEGIN_SRC python
154+
random.setstate(state)
155+
#+END_SRC
156+
157+
然后你会很神奇的发现,四个部分的代码所生成的随机数是一样的(不算上乘法与加法造成的差异).
158+
159+
在以后的博文中,我还会展示随机数的其他用法,例如可以用来对字符串做一些事情,敬请期待吧.
160+
161+
* Footnotes
162+
163+
[fn:1] 严格来说,这些都是尾随机数(PRNGs),但是为了简便,让我们就认为是真正的随机数吧.
164+
165+
* Local Variables Setting
166+
# Local Variables:
167+
# org-babel-default-header-args:python: ((:session . "random") (:results . "output") (:exports . "both") (:cache))
168+
# org-babel-python-command: "python3"
169+
# End:

0 commit comments

Comments
 (0)