繁体   English   中英

在python shell中执行bash的复杂find命令

[英]executing bash's complex find command in python shell

我是python的新手。 我正在尝试在python中执行bash脚本以提取不同文件扩展名的数量。 我尝试了以下命令

import subprocess
output = subprocess.check_output("sudo find . -type f -name '*.*' -exec sh -c 'echo ${0##*.}' {} \; | sort | uniq -c | sort -nr | awk '{print $2 ":" $1}'", shell=True)

但这会引发语法错误。 在bash shell中执行find命令

sudo find . -type f -name '*.*' -exec sh -c 'echo ${0##*.}' {} \; | sort | uniq -c | sort -nr | awk '{print $2 ":" $1}'

输出如下

png:3156
json:333
c:282
svg:241
zsh:233
js:192
gz:169
zsh-theme:143
ttf:107
cache:103
md:93

那么如何在python代码中获得相同的输出呢? 我当前的方法需要进行哪些更正? 提前致谢

如注释中所述,用双引号引起来的字符串中的任何双引号都需要使用反斜杠进行转义:

import subprocess
output = subprocess.check_output("sudo find . -type f -name '*.*' -exec sh -c 'echo ${0##*.}' {} \; | sort | uniq -c | sort -nr | awk '{print $2 \":\" $1}'", shell=True)

双引号字符串中的单引号没有任何特殊含义(直接在开头除外),因此不允许您转义。

详细信息在Python语言参考的标头String和Bytes文字下进行了说明

如评论中所述,另一个选项(可能更容易阅读)是使用三重双引号:

import subprocess
output = subprocess.check_output("""sudo find . -type f -name '*.*' -exec sh -c 'echo ${0##*.}' {} \; | sort | uniq -c | sort -nr | awk '{print $2 ":" $1}'""", shell=True)

在回答这个问题的同时,为了易于阅读和可维护性,我建议将其完全替换为Python,如另一个答案所示。

顺便说一句,您可以尝试在纯Python中执行相同的操作。 这是执行此操作的最小代码:

import os

def count_all_ext ( path ):
    res = {}
    for root,dirs,files in os.walk( path ):
        for f in files :
            if '.' in f :
                e = f.rsplit('.',1)[1]
                res[e] = res.setdefault(e,0)+1
    return res.items()


print '\n'.join( '%s:%d'%i for i in count_all_ext('.'))

好的,与Bash片段相比,它很长,但是它是Python ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM