2017-08-15 60 views
3

我想從python程序運行bash腳本。該腳本有這樣的命令:如何在Python中運行這個shell腳本?

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

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

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

但在這裏那是因爲引用的跡象是不可能的。有什麼建議麼?

謝謝!

+5

你可以使用'\'逃避'''標記嗎? – ifconfig

+0

哇。它確實工作。我不認爲它會起作用,因爲另一個命令正在進入每個子目錄。謝謝! – 0x1

+0

可能的重複[爲什麼'(單引號)或「(雙引號)不允許在Python中的subprocess.check \ _output()?](https://stackoverflow.com/questions/22224800/why-are-single -quote-或雙引號,不被允許功能於子 - 檢查 - outpu) – agtoever

回答

3

\'標記換算出去。

對於每個:',替換爲:\'

2

三重引號或三雙引號(「」「一些字符串」「」或「」「其他一些字符串」「」)是很方便的,以及。見here(是的,它的python3文件,但它們都工作在python2 100%)

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

雖然問題已經回答了,我還是會跳,因爲我認爲你要執行的是bash腳本,因爲你沒有功能上等效的Python代碼(基本上這比40行更糟糕,見下文)。 爲什麼這個而不是bash腳本?

  • 你的腳本現在能夠對具有Python解釋器的任何操作系統上運行
  • 功能是一個更容易閱讀和理解
  • 如果你需要什麼特別的,它總是更容易適應您的自己的代碼
  • 更Python :-)

記住,是請緊(如您的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()