首页 > 解决方案 > 在 Python 中使用 concurrent.future 实现多线程

问题描述

我编写了一个 python 代码,将原始数据(STM 显微镜)转换为 png 格式,它可以在我的 Macbook Pro 上完美运行。

下面是简化的 Python 代码:

for root, dirs, file in os.walk(path):
    for dir in dirs:
        fpath = path +'/'+ dir
        os.chdir(fpath)
        spaths=savepath +'/'+ dir
        if os.path.exists(spaths) ==False:
           os.mkdir(spaths)

         for files in glob.glob("*.sm4"):
             for file in files:     
                 data_conv (files, file, spaths)

但是 100 个文件确实需要 30 - 40 分钟。

现在,我想使用多线程技术(使用“并发未来”库)来减少处理时间。以“Python 线程教程”中的 YouTube 视频为例,尝试修改 Python 代码。

但是我必须在 executor.map() 方法中传递太多参数,例如“root”、“dirs.”、“file”。我不知道如何进一步解决这个问题。

下面是简化的多线程 Python 代码

def raw_data (root, dirs, file):
    for dir in dirs:
        fpath = path +'/'+ dir
        os.chdir(fpath)
        spaths=savepath +'/'+ dir
        if os.path.exists(spaths)==False:
            os.mkdir(spaths)

        for files in glob.glob("*.sm4"):
            for file in files:
                data_conv(files, file, spaths)

with concurrent.futures.ThreadPoolExecutor() as executor:
     executor.map(raw_data, root, dirs, file)

NameError: name 'root' is not defined

任何建议表示赞赏,谢谢。

标签: pythonpython-3.xmultithreadingpython-multithreadingconcurrent.futures

解决方案


感谢 Iain Shelvington 和 Thenoneman 的建议。

Pathlib确实减少了我在代码中的混乱。

“ProcessPoolExecutor”在我的 CPU 密集型功能中工作。

  with concurrent.futures.ProcessPoolExecutor() as executor:
        executor.map(raw_data, os.walk(path))

推荐阅读