Perl 有一个可爱的小实用程序,称为find2perl,它将(非常忠实地)将 Unix 实用程序的命令行find
转换为 Perl 脚本以执行相同的操作。
如果您有这样的查找命令:
find /usr -xdev -type d -name '*share'
^^^^^^^^^^^^ => name with shell expansion of '*share'
^^^^ => Directory (not a file)
^^^ => Do not go to external file systems
^^^ => the /usr directory (could be multiple directories
它找到所有以share
下面结尾的目录/usr
现在运行find2perl /usr -xdev -type d -name '*share'
,它会发出一个 Perl 脚本来做同样的事情。然后,您可以修改脚本以供您使用。
Python 有os.walk()
其中当然有需要的功能,递归目录列表,但是有很大的不同。
以find . -type f -print
查找并打印当前目录下的所有文件为例。一个天真的实现使用os.walk()
将是:
for path, dirs, files in os.walk(root):
if files:
for file in files:
print os.path.join(path,file)
find . -type f -print
但是,这将产生与在 shell 中键入不同的结果。
我也一直在测试各种 os.walk() 循环:
# create pipe to 'find' with the commands with arg of 'root'
find_cmd='find %s -type f' % root
args=shlex.split(find_cmd)
p=subprocess.Popen(args,stdout=subprocess.PIPE)
out,err=p.communicate()
out=out.rstrip() # remove terminating \n
for line in out.splitlines()
print line
不同之处在于 os.walk() 将链接计为文件;find 跳过这些。
因此,与以下相同的正确实现file . -type f -print
变为:
for path, dirs, files in os.walk(root):
if files:
for file in files:
p=os.path.join(path,file)
if os.path.isfile(p) and not os.path.islink(p):
print(p)
由于存在数百种查找初选和不同副作用的排列,因此测试每个变体变得非常耗时。由于find
是 POSIX 世界中关于如何计算树中文件的黄金标准,因此在 Python 中以同样的方式进行操作对我来说很重要。
find2perl
那么有没有可以用于 Python的等价物?到目前为止,我一直在使用find2perl
并手动翻译 Perl 代码。这很难,因为 Perl 文件测试运算符有时与 os.path 中的 Python 文件测试不同。