python子进程.Popen

2024-06-16 14:44:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解如何让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用我的搜索字符串构建另一个文件。


Tags: thelogbinusrstdoutlinefilelogs
3条回答

不完全确定您的问题,但下面的代码片段将使用两个参数调用zgrep,一个是searchterm,一个是filename-并逐行打印结果(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'"

问题在于你如何构建你的论点。你现在的样子,你在跑:

/usr/bin/zgrep /meatsauce/ logs/consolidated.log.gz

注意/meatsauce/logs之间的空格。。。

要做我想做的事,使用os.path.joina 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
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)

相关问题 更多 >