使用一组工作人员编写文件

2024-09-30 08:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须写一些相当大的文件,我想在一个单独的线程(同时使用处理器和硬盘驱动器)和我想使用一个大小为4的工人池(因为除了写,还有其他操作,我想4足够正常使用硬盘驱动器,而不堵塞它)。在

这是我的代码(它什么也不做):

import os, os.path, multiprocessing

def asyncFileMake(e):
    with open('files/file%d.txt'%e, 'w') as f:
        print(os.path.dirname(os.path.abspath(os.getcwd())))
        f.write("hi")

def writefile(e, pool):
    pool.apply_async(asyncFileMake, [e])

if __name__ == "__main__":
    if not os.path.exists('files'):
        os.makedirs('files')
    with multiprocessing.Pool(processes=4) as pool:
        for e in range(10):
          writefile(e, pool)

Tags: 文件pathifosdefaswithfiles
1条回答
网友
1楼 · 发布于 2024-09-30 08:34:12

这里有一个版本,它的灵感来自于您的原始代码片段。我认为最重要的变化是函数传递到池的方式(map而不是{},稍后将详细介绍):

import os
import multiprocessing

def create_file(e):
    with open('files/file%d.txt'%e, 'w') as f:
        print f.name
        f.write("hi")

if __name__ == '__main__':
    if not os.path.exists('files'):
            os.makedirs('files')
    pool = multiprocessing.Pool(processes=4)
    pool.map(create_file, range(10))

原始实现的问题是,pool.apply_async返回一个AsyncResult,您需要调用get以便触发实际执行。我建议你再仔细看看documentation of multiprocessing。尤其是this part about pool workers。希望有帮助。在

相关问题 更多 >

    热门问题