在Python3中使用多重处理读取文件

时间:2019-04-29 14:26:17

标签: python python-3.x python-multiprocessing

我的文件非常大。每个文件将近2GB。因此,我想并行运行多个文件。我可以这样做,因为所有文件的格式都相似,因此可以并行读取文件。我知道我应该使用多处理库,但是我真的很困惑如何在我的代码中使用它。

我用于读取文件的代码是:

def file_reading(file,num_of_sample,segsites,positions,snp_matrix):
    with open(file,buffering=2000009999) as f:
        ###I read file here. I am not putting that code here.
        try:
            assert len(snp_matrix) == len(positions)
            return positions,snp_matrix ## return statement
        except:
            print('length of snp matrix and length of position vector not the same.')
            sys.exit(1)

我的主要功能是:

if __name__ == "__main__":    
    segsites = []
    positions = []
    snp_matrix = []




    path_to_directory = '/dataset/example/'
    extension = '*.msOut'

    num_of_samples = 162
    filename = glob.glob(path_to_directory+extension)

    ###How can I use multiprocessing with function file_reading
    number_of_workers = 10

   x,y,z = [],[],[]

    array_of_number_tuple = [(filename[file], segsites,positions,snp_matrix) for file in range(len(filename))]
    with multiprocessing.Pool(number_of_workers) as p:
        pos,snp = p.map(file_reading,array_of_number_tuple)
        x.extend(pos)
        y.extend(snp)

因此我对该函数的输入如下:

  1. 文件-包含文件名的列表
  2. num_of_samples-整数值
  3. segsites-最初是一个空列表,我在读取文件时要附加到其中。
  4. 位置-最初是一个空列表,我在阅读文件时要附加到该列表。
  5. snp_matrix-最初是一个空列表,我在读取文件时要附加到其中。

该函数最后返回位置列表和snp_matrix列表。在参数为列表和整数的情况下,如何使用多重处理?我使用多重处理的方式给我以下错误:

TypeError:file_reading()缺少3个必需的位置参数:“ segsites”,“ positions”和“ snp_matrix”

1 个答案:

答案 0 :(得分:1)

传递到Pool.map的列表中的元素不会自动解压缩。通常,“ file_reading”函数中只能有一个参数。

当然,该参数可以是一个元组,因此自己解压缩是没有问题的:

def file_reading(args):
    file, num_of_sample, segsites, positions, snp_matrix = args
    with open(file,buffering=2000009999) as f:
        ###I read file here. I am not putting that code here.
        try:
            assert len(snp_matrix) == len(positions)
            return positions,snp_matrix ## return statement
        except:
             print('length of snp matrix and length of position vector not the same.')
            sys.exit(1)

if __name__ == "__main__":    
    segsites = []
    positions = []
    snp_matrix = []

    path_to_directory = '/dataset/example/'
    extension = '*.msOut'

    num_of_samples = 162
    filename = glob.glob(path_to_directory+extension)

    number_of_workers = 10

    x,y,z = [],[],[]


    array_of_number_tuple = [(filename[file], num_of_samples, segsites,positions,snp_matrix) for file in range(len(filename))]
    with multiprocessing.Pool(number_of_workers) as p:
        pos,snp = p.map(file_reading,array_of_number_tuple)
        x.extend(pos)
        y.extend(snp)