2016-11-24 26 views
1

我想在Python才能執行此命令Python的調用grep的失敗

grep keyMessage logFile.log > keyMessageFile.log 

這就是我現在做

from subprocess import call 

keyMessage= 'keyMessage' 
call(["grep", keyMessage, "logFile.log"]) 

,但我不知道如何添加> keyMessageFile.log部分

順便說一下,我使用grep的原因是因爲它比使用讀文件快得多,然後比較字符串,然後寫文件

#UPDATE 有較慢Python代碼寫到

keyMessage= 'keyMessage' 

with open('logFile.log') as f: 
    for line in f: 
     with open(keyMessage+ '.txt', 'a') as newFile: 
      if(keyMessage not in line): 
       continue 
      else: 
       newFile.write(line) 
+0

爲什麼從'python'調用'grep'? – cdarke

+0

@MichaelMao您的更新代碼將打開並關閉每行的輸出文件,該文件仍然很慢。 – AKX

回答

4

,最簡單的方式做到這一點(合理的安全太)是:

from subprocess import check_call 
from shlex import quote 
check_call('grep %s logFile.log > keyMessageFile.log' % quote(keyMessage), shell=True) 

但是除非你真的需要的grep正則表達式匹配能力,和你最終讀程序keyMessageFile.log反正,我不牛逼認爲以下是不合理的慢:

def read_matching_lines(filename, key): 
    with open(filename) as fp: 
     for line in fp: 
     if key in line: 
      yield line 

for matching_line in read_matching_lines('logFile.log', keyMessage): 
    print(matching_line) 
+0

「*除非你確實需要grep *的正則表達式匹配功能」 - python的正則表達式能力有什麼問題? – cdarke

+0

對不起,我不明白你給的第二個樣本。該函數名爲read_matching_lines或read_matching_files,什麼是matching_line – MichaelMao

+0

我明白了,第二個示例比我的Python代碼更快。謝謝 – MichaelMao

4

subprocess.call具有參數stdout。傳遞打開的文件以寫入文件。

with open("keyMessageFile.log", "w") as o: 
    keyMessage= 'keyMessage' 
    call(["grep", keyMessage, "logFile.log"], stdout=o) 

subprocess.call是舊的API,你應該使用subprocess.run代替。

0

對於我這樣工作的:

import sys 
    os.system('grep %s logFile.log > keyMessageFile.log' % 'looking string')