python subprocess.Popen使用方法

1 投票
4 回答
12048 浏览
提问于 2025-04-16 20:02

我在理解如何用 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 根据我的搜索字符串生成另一个文件。

4 个回答

1

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这时候,我们可以去一些技术论坛,比如StackOverflow,去寻找解决方案或者向其他人请教。

在这些论坛上,很多人会分享他们的经验和解决方法。你可以看到别人是如何解决类似的问题,或者他们是如何理解某些技术概念的。这对于刚开始学习编程的人来说,特别有帮助。

总之,StackOverflow是一个很好的地方,可以让你学习到很多实用的知识和技巧,帮助你更好地理解编程的世界。

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)
2

问题出在你构建参数的方式上。你现在的写法是:

/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
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'"

撰写回答