簡體   English   中英

如何在python中運行這個shell腳本?

[英]How can I run this shell script inside python?

我想從python程序運行一個bash腳本。 腳本有這樣的命令:

find . -type d -exec bash -c 'cd "$0" && gunzip -c *.gz | cut -f 3 >> ../mydoc.txt' {} \;

通常我會運行一個子進程調用,如:

subprocess.call('ls | wc -l', shell=True)

但由於引用的跡象,這在那里是不可能的。 有什么建議?

謝謝!

雖然問題已經得到解答,但我仍然會跳進去,因為我假設您要執行該bash腳本,因為您沒有功能相同的Python代碼(基本上比40行更糟糕,見下文)。 為什么這樣做而不是bash腳本?

  • 您的腳本現在可以在任何具有Python解釋器的操作系統上運行
  • 該功能更易於閱讀和理解
  • 如果您需要任何特殊功能,則可以更輕松地調整自己的代碼
  • 更多Pythonic :-)

請記住(作為您的bash腳本)沒有任何錯誤檢查,輸出文件是一個全局變量,但可以輕松更改。

import gzip
import os

# create out output file
outfile = open('/tmp/output.txt', mode='w', encoding='utf-8')

def process_line(line):
    """
    get the third column (delimiter is tab char) and write to output file
    """
    columns = line.split('\t')
    if len(columns) > 3:
        outfile.write(columns[3] + '\n')

def process_zipfile(filename):
    """
    read zip file content (we assume text) and split into lines for processing
    """
    print('Reading {0} ...'.format(filename))
    with gzip.open(filename, mode='rb') as f:
        lines = f.read().decode('utf-8').split('\n')
        for line in lines:
            process_line(line.strip())


def process_directory(dirtuple):
    """
    loop thru the list of files in that directory and process any .gz file
    """
    print('Processing {0} ...'.format(dirtuple[0]))
    for filename in dirtuple[2]:
        if filename.endswith('.gz'):
            process_zipfile(os.path.join(dirtuple[0], filename))

# walk the directory tree from current directory downward
for dirtuple in os.walk('.'):
    process_directory(dirtuple)

outfile.close()

\\逃避'標記'

對於每一個: ' ,替換為: \\'

三重引號或三重雙引號('''some string'''或“”“其他字符串”“”)也很方便。 看到這里 (是的,它的python3文檔,但它在python2中100%工作)

mystring = """how many 'cakes' can you "deliver"?"""
print(mystring)
how many 'cakes' can you "deliver"?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM