[英]Python subprocess library: Running grep command from Python
我正在嘗試使用子進程庫從我的Python模塊運行grep命令。 由於我在doc文件上執行此操作,因此我在使用Catdoc第三方庫來獲取計划文本文件中的內容。 我想將內容存儲在文件中。 我不知道我要去哪里錯了,但是程序無法生成純文本文件,最終無法獲得grep結果。 我已經通過錯誤日志,但它為空。 感謝您的所有幫助。
def search_file(name, keyword):
#Extract and save the text from doc file
catdoc_cmd = ['catdoc', '-w' , name, '>', 'testing.txt']
catdoc_process = subprocess.Popen(catdoc_cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
output = catdoc_process.communicate()[0]
grep_cmd = []
#Search the keyword through the text file
grep_cmd.extend(['grep', '%s' %keyword , 'testing.txt'])
print grep_cmd
p = subprocess.Popen(grep_cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
stdoutdata = p.communicate()[0]
print stdoutdata
在UNIX上,指定shell=True
將導致第一個參數被視為要執行的命令,而所有后續參數均被視為shell本身的參數 。 因此, >
不會有任何效果(因為使用/bin/sh -c
,該命令之后的所有參數都將被忽略)。
因此,您應該實際使用
catdoc_cmd = ['catdoc -w "%s" > testing.txt' % name]
不過,更好的解決方案可能是僅從子進程的stdout
讀取文本,然后使用re
或Python字符串操作對其進行處理:
catdoc_cmd = ['catdoc', '-w' , name]
catdoc_process = subprocess.Popen(catdoc_cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
for line in catdoc_process.stdout:
if keyword in line:
print line.strip()
我認為您正在嘗試將>傳遞給shell,但這不會按照您的方式進行。 如果要生成一個進程,則應安排其標准重定向。 幸運的是,這確實很容易做到。 您要做的就是打開要輸出的文件以寫入,然后使用stdout關鍵字參數而不是PIPE將其傳遞給popen,這將導致該文件附加到可以通過communication()讀取的管道上。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.