簡體   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