作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我用 Java 编写了一个简单的应用程序,它采用路径列表并生成一个文件,其中包含该原始列表下的所有文件路径。
如果我的 paths.txt 包含:
c:\folder1\
c:\folder2\
...
...
c:\folder1000\
我的应用程序在每个路径上多线程运行递归函数,并返回一个文件,其中包含这些文件夹下的所有文件路径。
现在我想用 Python 编写这个应用程序。
我编写了一个简单的应用程序,它使用 os.walk()
运行给定文件夹并打印文件路径以输出。
现在我想并行运行它,并且我已经看到 Python 有一些用于此目的的模块:多线程和多处理。
最好的方法是什么?而在这种方式下,它是如何执行的?
最佳答案
这是一个多处理解决方案:
from multiprocessing.pool import Pool
from multiprocessing import JoinableQueue as Queue
import os
def explore_path(path):
directories = []
nondirectories = []
for filename in os.listdir(path):
fullname = os.path.join(path, filename)
if os.path.isdir(fullname):
directories.append(fullname)
else:
nondirectories.append(filename)
outputfile = path.replace(os.sep, '_') + '.txt'
with open(outputfile, 'w') as f:
for filename in nondirectories:
print >> f, filename
return directories
def parallel_worker():
while True:
path = unsearched.get()
dirs = explore_path(path)
for newdir in dirs:
unsearched.put(newdir)
unsearched.task_done()
# acquire the list of paths
with open('paths.txt') as f:
paths = f.read().split()
unsearched = Queue()
for path in paths:
unsearched.put(path)
with Pool(5) as pool:
for i in range(5):
pool.apply_async(parallel_worker)
unsearched.join()
print('Done')
关于python - 如何在 Python 中并行运行 os.walk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11920490/
我是一名优秀的程序员,十分优秀!