python subprocess.Popen

| 我很难理解如何使用
subprocess.Popen
函数使python调用系统命令。
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用我的搜索字符串构建另一个文件。     
已邀请:
        问题在于您如何构造参数。现在,您正在运行:
/usr/bin/zgrep /meatsauce/ logs/consolidated.log.gz
注意
/meatsauce/
logs
之间的空格... 要执行我认为您打算的操作,请使用
os.path.join
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
    
        不确定您的问题,但是以下代码片段将使用两个参数(搜索项和文件名)调用
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\'\"
    
        
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)
    
        我认为您只是在尝试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\'])
还要检查文档。     

要回复问题请先登录注册