在python中使用Multiprocessing转换多个文件

时间:2017-03-28 08:37:00

标签: python multiprocessing

我在这个网站上寻求答案,但没有发现。我的问题是我想在python中将几个文件从一种格式转换为另一种格式。我想同时转换4个文件。我已经使用多处理库中的process关键字创建了一个代码,它可以工作,但是它使用了几个进程来逐个转换文件,这不是我想要的。我试着用这段代码同时转换它们:

def convert_all_files (directoryName):
  directoryName = r'Here I set my directory name C:\...'
  files2=[]
  pool=mp.Pool(4)
  for path, dirs, files in os.walk(directoryName):
    for f in files:
      f1=f
      path1=path        
      files2.append((path1,f1))
  for j in range(0, len(files2)):
    pool.apply_async(convert, (files2[j][0],files2[j][1]))
  pool.close()
  pool.join()

我的问题是代码运行,但是函数convert没有被执行,并且代码冻结在行pool.join()(我使用这种技术来获得很多时间,因为转换很长,当我运行此代码,转换是即时的,不起作用。)

我在另一个文件中使用上面定义的函数。我导入我的模块并调用该函数。

有没有人有想法? 感谢

1 个答案:

答案 0 :(得分:0)

这是一个有效的解决方案,同时没有4次转换的限制。

def convert_all_files(directoryName):
    for folder, subs, files in os.walk(directoryName):
        for filename in files:
            p = Process(target=convert, args=(folder, filename))
            p.start()

如果您需要限制,这是一个解决方案,但我不确定这是最好的:

def convert_all_files(directoryName):
    process_count = 0
    for folder, subs, files in os.walk(directoryName):
        for filename in files:
            p = Process(target=convert, args=(folder, filename))
            p.start()

            # Maybe not the better way to handle it
            process_count = process_count + 1
            if process_count % 4 == 0:
                p.join()