简体   繁体   English

python subprocess.Popen

[英]python subprocess.Popen

I am having a difficult time understanding how to get python to call a system command with the subprocess.Popen function. 我很难理解如何让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

Trying to get python to build another file with my search string. 试图让python用我的搜索字符串构建另一个文件。

The problem is in how you're constructing your arguments. 问题在于您如何构造参数。 The way you have it now, you're running: 现在,您正在运行:

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

Note the space between /meatsauce/ and logs ... 注意/meatsauce/logs之间的空间...

To do what I think you're intending, use os.path.join a la: 要执行我认为您打算的操作,请使用os.path.join 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

Not exactly sure about your question, but the following snippet will call zgrep with two arguments, a searchterm and a filename - and print the result ( stdout ) line by 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

In the code you posted the string interpolation ( % dpt_search ) does not work out, since there is not pure string in front of the modulo sign - in fact it should fail with something like: 在您发布的代码中,字符串插值( % 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)

I think you are simply trying to grep the a content in the a file. 我认为您只是在尝试grep文件中的内容。 Is it? 是吗?

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'])

Check the docs as well. 还要检查文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM