我正在尝试实现一个处理大型csv文件的multiprocessing
模块。我正在使用Python 2.7,并遵循here中的示例。
我运行了未修改的代码(为了方便起见,下面复制了代码),并注意到worker
函数中的print
语句不起作用。无法print
使理解流程和调试变得困难。
有人能解释一下为什么print
不在这里工作吗?pool.map不执行打印命令吗?我在网上搜索,但没有找到任何文件表明这一点。
import multiprocessing as mp
import itertools
import time
import csv
def worker(chunk):
# `chunk` will be a list of CSV rows all with the same name column
# replace this with your real computation
print(chunk) # <----- nothing prints
print 'working' # <----- nothing prints
return len(chunk)
def keyfunc(row):
# `row` is one row of the CSV file.
# replace this with the name column.
return row[0]
def main():
pool = mp.Pool()
largefile = 'test.dat'
num_chunks = 10
results = []
with open(largefile) as f:
reader = csv.reader(f)
chunks = itertools.groupby(reader, keyfunc)
while True:
# make a list of num_chunks chunks
groups = [list(chunk) for key, chunk in
itertools.islice(chunks, num_chunks)]
if groups:
result = pool.map(worker, groups)
results.extend(result)
else:
break
pool.close()
pool.join()
print(results)
if __name__ == '__main__':
main()
这是IDLE的问题,您使用它来运行代码。IDLE对终端进行了一个相当基本的模拟,用于处理在其中运行的程序的输出。但是它不能处理子流程,所以虽然它们在后台运行得很好,但是您永远看不到它们的输出。
最简单的修复方法是从命令行运行代码。
另一种选择可能是使用更复杂的IDE。在the Python wiki中列出了很多,但我不确定哪一个对于多处理输出有更好的终端仿真。
相关问题 更多 >
编程相关推荐