Python:多处理无法完成作业

时间:2017-06-06 17:49:07

标签: python multiprocessing python-multiprocessing pool

我使用python 2.7和multiprocessing :: Pool并行运行作业

我已经简化了下面的例子,但这里是它的主要要点。

它将使用apply_async()函数为我的dict中的每个人创建一个文件。但是,当我检查文件是否正确创建时,我注意到有时文件未创建。

现在我想我在使用多处理方面做错了什么:: Pool

有什么建议吗?

import os
from multiprocessing import Pool

def outputFile(person):
    ofh=open(person+'.txt','w')
    ofh.write('test\n')
    ofh.close()

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputFile,args(person))
pool.close()
pool.join()
for person in person_dict:
    print os.path.isfile(person+'.txt')
True
True
False
True

2 个答案:

答案 0 :(得分:1)

这可能与person_dict的内容有关吗?

我修改了你的代码并运行了几次。他们都产生了预期的结果。

以下是我修改和测试的代码:

import os
from multiprocessing import Pool

def outputfile(person):
    with open(person+'.txt','w') as ofh:
        ofh.write('test\n')

person_dict = {'a': 'a', 'b': 'b', 'c':'c', 'd':'d'}

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputfile, (person))
pool.close()
pool.join()

for person in person_dict:
    print(os.path.isfile(person+'.txt'))

答案 1 :(得分:1)

如果您没有捕获子流程中的异常并自行打印,您将看不到它们。以下程序不产生输出:

import os
from multiprocessing import Pool

def outputFile(person):
    raise Exception("An exception")

pool = Pool(processes=4)
for person in range(100):
    pool.apply_async(outputFile, args=(person,))
pool.close()
pool.join()

您需要捕获所有异常并手动打印回溯:

import os
from multiprocessing import Pool, Lock
import traceback

print_lock = Lock()

def outputFile(person):
    try:
        raise Exception("An exception")
    except:
        with print_lock:
            print "%s: An exception occurred" % person
            print traceback.format_exc()

pool = Pool(processes=4)
for person in range(100):
    args = (person, print_lock)
    pool.apply_async(outputFile, args=(person,))
pool.close()
pool.join()

<强>输出

0: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception

1: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception

...

99: An exception occurred
Traceback (most recent call last):
  File "person.py", line 9, in outputFile
    raise Exception("An exception")
Exception: An exception

注意: print_lock用于防止输出交错。