【发布时间】:2015-11-25 21:49:52
【问题描述】:
我正在试验多处理模块并从this 页面复制示例代码。这是一个例子:
#!/usr/bin/python
from multiprocessing import Pool
from time import sleep
def f(x):
return x*x
if __name__ == '__main__':
# start 4 worker processes
with Pool(processes=4) as pool:
# print "[0, 1, 4,..., 81]"
print(pool.map(f, range(10)))
# print same numbers in arbitrary order
for i in pool.imap_unordered(f, range(10)):
print(i)
# evaluate "f(10)" asynchronously
res = pool.apply_async(f, [10])
print(res.get(timeout=1)) # prints "100"
# make worker sleep for 10 secs
res = pool.apply_async(sleep, [10])
print(res.get(timeout=1)) # raises multiprocessing.TimeoutError
# exiting the 'with'-block has stopped the pool
运行此代码后,我得到:
Traceback (most recent call last):
File "example01.py", line 11, in <module>
with Pool(processes=4) as pool:
AttributeError: __exit__
不知何故,我发现这是由于 with 关键字。然而,这段代码也在使用with 并且它正在运行:
#!/usr/bin/python
with open("input.csv", "wb") as filePath:
pass
filePath.close()
当我想运行提到的示例时,我必须按照以下方式对其进行修改:
#!/usr/bin/python
from multiprocessing import Pool
from time import sleep
import traceback
def f(x):
return x*x
if __name__ == '__main__':
# start 4 worker processes
# with Pool(processes=4) as pool:
try:
pool = Pool(processes = 4)
# print "[0, 1, 4,..., 81]"
print(pool.map(f, range(10)))
# print same numbers in arbitrary order
for i in pool.imap_unordered(f, range(10)):
print(i)
# evaluate "f(10)" asynchronously
res = pool.apply_async(f, [10])
print(res.get(timeout=1)) # prints "100"
# make worker sleep for 10 secs
res = pool.apply_async(sleep, [10])
print(res.get(timeout=1)) # raises multiprocessing.TimeoutError
# exiting the 'with'-block has stopped the pool
# http://stackoverflow.com/questions/4990718/python-about-catching-any-exception
# http://stackoverflow.com/questions/1483429/how-to-print-an-error-in-python
# http://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for
except Exception as e:
print "Exception happened:"
print type(e)
print str(e)
print traceback.print_exc()
然后输出如下所示:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
0
1
4
9
16
25
36
49
64
81
100
Exception happened:
<class 'multiprocessing.TimeoutError'>
Traceback (most recent call last):
File "example01_mod.py", line 29, in <module>
print(res.get(timeout=1)) # raises multiprocessing.TimeoutError
File "/usr/lib/python2.7/multiprocessing/pool.py", line 563, in get
raise TimeoutError
TimeoutError
None
为什么我在使用 with 关键字时会出错,这些代码(带有和 try-catch)是等效的吗?我正在使用 python 2.7.10。
【问题讨论】:
-
您不能只将
with用于任何对象。对象必须是context manager。