python - 在 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
任何建议表示赞赏,谢谢。
解决方案
感谢 Iain Shelvington 和 Thenoneman 的建议。
Pathlib确实减少了我在代码中的混乱。
“ProcessPoolExecutor”在我的 CPU 密集型功能中工作。
with concurrent.futures.ProcessPoolExecutor() as executor:
executor.map(raw_data, os.walk(path))
推荐阅读
- virsh - 解析 virsh 输出
- java - 为什么要两个列表
- azure-devops - 在不属于先前分支的分支上获取所有提交
- c++ - 为什么我们在 C++ 项目中需要头文件?
- c++ - 为什么 -Wfatal-errors 会关闭有关错误的注释,以及如何重新打开注释?
- apache-spark - Spark 任务数与分区数
- powershell - 通过 Powershell 进行的 Azure AD 身份验证返回 null
- ruby-on-rails - ActiveStorage::PurgeJob:Class (NoMethodError) 的未定义方法“discard_on”
- python - #days 上的移动平均值,使用 Pandas 每天变化的观察次数
- deployment - 上限生产部署失败并出现 ActiveRecord::NoDatabaseError: FATAL: 数据库“rails/rbwapp”不存在