【发布时间】:2020-04-03 17:25:57
【问题描述】:
我尝试通过使用 os.scandir() 而不是 os.listdir() 在 Windows 上优化用 Python 编写的文件浏览功能。但是,时间保持不变,大约 2 分半钟,我不知道为什么。 以下是功能,原始和更改:
os.listdir() 版本:
def browse(self, path, tree):
# for each entry in the path
for entry in os.listdir(path):
entity_path = os.path.join(path, entry)
# check if support by git or not
if self.git_ignore(entity_path) is False:
# if is a dir create a new level in the tree
if os.path.isdir( entity_path ):
tree[entry] = Folder(entry)
self.browse(entity_path, tree[entry])
# if is a file add it to the tree
if os.path.isfile(entity_path):
tree[entry] = File(entity_path)
os.scandir() 版本:
def browse(self, path, tree):
# for each entry in the path
for dirEntry in os.scandir(path):
entry_path = dirEntry.name
entity_path = dirEntry.path
# check if support by git or not
if self.git_ignore(entity_path) is False:
# if is a dir create a new level in the tree
if dirEntry.is_dir(follow_symlinks=True):
tree[entry_path] = Folder(entity_path)
self.browse(entity_path, tree[entry_path])
# if is a file add it to the tree
if dirEntry.is_file(follow_symlinks=True):
tree[entry_path] = File(entity_path)
另外,这里使用的辅助函数如下:
def git_ignore(self, filepath):
if '.git' in filepath:
return True
if '.ci' in filepath:
return True
if '.delivery' in filepath:
return True
child = subprocess.Popen(['git', 'check-ignore', str(filepath)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output = child.communicate()[0]
status = child.wait()
return status == 0
============================================================
class Folder(dict):
def __init__(self, path):
self.path = path
self.categories = {}
============================================================
class File(object):
def __init__(self, path):
self.path = path
self.filename, self.extension = os.path.splitext(self.path)
有没有人可以解决如何使函数运行得更快?我的假设是在开始时提取名称和路径会使其运行速度比应有的慢,对吗?
【问题讨论】:
-
对于每个不包含“.git”、“.ci”或“.delivery”的路径,您正在生成一个 git 子进程。这很昂贵,如果你有很多这样的路径,那么生成和等待 git 进程所花费的累积时间将是一个瓶颈。
标签: python windows filesystems scandir listdir