Python,读取多个文件并合并结果

Bri*_*ian 5 python parallel-processing multiprocessing

我可能会问一个非常基本的问题,但我真的不知道如何在 python 中创建一个简单的并行应用程序。我正在一台具有 16 个核心的机器上运行我的脚本,我希望有效地使用所有这些核心。我有 16 个大文件要读取,我希望每个 cpu 读取一个文件,然后合并结果。在这里,我举一个简单的例子来说明我想做的事情:

  parameter1_glob=[]
  parameter2_glob[]


  do cpu in arange(0,16):
      parameter1,parameter2=loadtxt('file'+str(cpu)+'.dat',unpack=True)

      parameter1_glob.append(parameter1)
      parameter2_glob.append(parameter2)
Run Code Online (Sandbox Code Playgroud)

我认为该multiprocessing模块可能会有所帮助,但我无法理解如何将其应用到我想做的事情中。

Pau*_*ine 1

您想逐行合并吗?有时,对于 I/O 密集型应用程序来说,协程比经典的多任务处理更有趣。您可以链接生成器和协程以进行各种路由、合并和广播。David Beazley 的精彩演讲一定会让您大吃一惊。

您可以使用协程作为接收器(未经测试,请参考dabeaz示例):

# A sink that just prints the lines
@coroutine
def printer():
    while True:
        line = (yield)
        print line,

sources = [
    open('file1'),
    open('file2'),
    open('file3'),
    open('file4'),
    open('file5'),
    open('file6'),
    open('file7'),
]

output = printer()
while sources:
    for source in sources:
        line = source.next()
        if not line: # EOF
            sources.remove(source)
            source.close()
            continue
        output.send(line)
Run Code Online (Sandbox Code Playgroud)