我很难理解如何让python使用subprocess.Popen
函数调用系统命令。
the_file = ('logs/consolidated.log.gz')
webstuff = subprocess.Popen(['/usr/bin/zgrep', '/meatsauce/', the_file ],stdout=subprocess.PIPE)
for line in webstuff.stdout:
print line
尝试让python用我的搜索字符串构建另一个文件。
答案 0 :(得分:2)
问题在于你如何构建你的论点。你现在拥有它的方式,你正在运行:
/usr/bin/zgrep /meatsauce/ logs/consolidated.log.gz
请注意/meatsauce/
和logs
...
要做我认为你想要的事情,请使用os.path.join
a la:
import os
the_file = 'logs/consolidated.log.gz'
webstuff = subprocess.Popen(['/usr/bin/zgrep', os.path.join('/meatsauce/', the_file)],stdout=subprocess.PIPE) % dpt_search
for line in webstuff.stdout:
print line
答案 1 :(得分:2)
不完全确定您的问题,但以下代码段将使用两个参数(搜索项和文件名)调用zgrep
,并逐行打印结果(stdout
):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
# filename and searchterm
fn, term = 'access_log.gz', 'hello'
p = subprocess.Popen(['/usr/bin/zgrep', term, fn], stdout=subprocess.PIPE)
for line in p.stdout:
print line
在您发布的代码中,字符串插值(% dpt_search
)无效,因为模数符号前面没有纯字符串 - 事实上它应该会失败,例如:
TypeError: "unsupported operand type(s) for %: 'Popen' and 'str'"
答案 2 :(得分:1)
the_file = ('webalizerlogs/consolidated.log.gz')
output_f = open('output.txt','w')
webstuff = subprocess.Popen(['/usr/bin/zgrep', dpt_search, the_file ],stdout=output_f)
答案 3 :(得分:0)
我认为你只是试图grep一个文件中的内容。是吗?
import os
import subprocess
the_file = os.path.join(os.getcwd(),'logs/consolidated.log.gz')
proc = subprocess.Popen(['/usr/bin/zgrep', dpt_search, the_file], stdout=subprocess.PIPE)
out, err = proc.communicate()
with open('resultoutput','w') as f:
f.write(out)
subprocess.call(['/usr/bin/zip',os.path.join(os.getcwd(),'resultoutput'])
同时检查docs。