使用Python的手术室步行函数和ls命令

2024-06-01 10:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

#!/bin/python
import os
pipe=os.popen("ls /etc -alR| grep \"^[-l]\"|wc -l")         #Expr1
a=int(pipe.read())
pipe.close()
b=sum([len(files) for root,dirs,files in os.walk("/etc")])  #Expr2
print a
print b
print "a equals to b ?", str(a==b)  #False
print "Why?"

Expr1的函数和Expr2的函数有什么区别? 我认为Expr1给出了正确的答案,但不确定。在


Tags: 函数importbinosetcfileslsgrep
3条回答

如果使用walk,则忽略错误(请参见this),ls会为每个错误发送一条消息。这些都算作文字。在

简短回答:

ls -laR | grep "^[-l]"统计指向目录的符号链接。 它匹配任何以l开头并包含指向目录的符号链接的行。在

相反,[files for root, dirs, files in os.walk('/etc')]不计算指向目录的符号链接。它忽略所有目录,只列出文件。在


长回答:

以下是我如何识别差异:

import os
import subprocess
import itertools

def line_to_filename(line):
    # This assumes that filenames have no spaces, which is a false assumption
    # Ex: /etc/NetworkManager/system-connections/Wired connection 1
    idx = line.rfind('->')
    if idx > -1:
        return line[:idx].split()[-1]
    else:
        return line.split()[-1]

line_to_filename试图在ls -laR的输出中查找文件名。在

这定义了expr1和{},基本上与您的代码相同。在

^{pr2}$

这将从expr1中删除同时位于expr2中的名称:

for name in expr2:
    try:
        expr1.remove(name)
    except ValueError:
        print('{n} is not in expr1'.format(n = name))

删除expr1expr2共享的文件名之后

print(expr1) 

收益率

['i386-linux-gnu_xorg_extra_modules', 'nvctrl_include', 'template-dkms-mkdsc', 'run', '1', 'conf.d', 'conf.d']

然后我使用find/etc中找到这些文件,并试图猜测这些文件有什么不寻常之处。它们是指向目录(而不是文件)的符号链接。在

在我的机器上,/etc是指向/private/etc的符号链接,因此ls /etc只有一行输出。ls /etc/给出ls和{}之间的预期等价性。在

相关问题 更多 >