python - 在 Python3 中使用多处理进行文件读取
问题描述
我有非常大的文件。每个文件差不多 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)
所以我对该函数的输入如下:
- 文件 - 包含文件名的列表
- num_of_samples - 整数值
- segsites - 最初是一个空列表,我在读取文件时要附加到该列表中。
- 职位 - 最初是一个空列表,我在阅读文件时要附加到该列表中。
- snp_matrix - 最初是一个空列表,我在读取文件时要附加到该列表中。
该函数在最后返回位置列表和 snp_matrix 列表。在我的参数是列表和整数的情况下,如何使用多处理?我使用多处理的方式给了我以下错误:
类型错误:file_reading() 缺少 3 个必需的位置参数:“segsites”、“positions”和“snp_matrix”
解决方案
列表中传递给 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)
推荐阅读
- dart - 是否有关于如何使用 usr/passw 通过 SSH 登录路由器并与路由器提示交互的 DART 代码说明?(写入和读取cli)?
- .htaccess - 如何使用 htaccess 重定向规则将 301 重定向仅添加到 domain.com 的所有 404 错误页面(例如 domain.com/aaa)到精确的 newdomain.com/aaa 页面?
- java - 从 JSON 对象中的键中提取数据
- r - 来自 sjPlot 的 plot_likert 函数的自定义调色板
- php - PHP 在标签中搜索并获取另一个表的结果
- android - Flutter - 底部溢出 81 像素的 RenderFlex
- google-cloud-platform - 数据流作业失败:IP_SPACE_EXHAUSTED,IP 空间已用完
- java - Java 使用正则表达式限制用户输入
- azure - 如何使用复制活动将 csv 转换为 ADF 中的镶木地板?
- reactjs - React js OIdc-Client 如何访问用户声明和角色