【问题标题】:python how to use subprocess pipe with linux shellpython如何在linux shell中使用子进程管道
【发布时间】:2017-02-18 07:05:49
【问题描述】:

我有一个 python 脚本搜索日志,它不断输出找到的日志,我想使用 linux 管道来过滤所需的输出。像这样的例子:

$python logsearch.py​​ | grep 超时

问题是 sort 和 wc 一直阻塞,直到 logsearch.py​​ 完成,而 logsearch.py​​ 会不断输出结果。

示例 logsearch.py​​:

p = subprocess.Popen("ping google.com", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in p.stdout:
    print(line)

更新:

想通了,把子进程中的stdout改成sys.stdout,python会帮你处理管道的。

p = subprocess.Popen("ping -c 5 google.com", shell=True, stdout=**sys.stdout**)

感谢大家的帮助!

【问题讨论】:

  • ping -c 5 是一个永远运行的脚本的奇怪示例!但是,是的,在你拥有所有东西之前,你无法对事物进行排序或计算事物的数量。
  • @tdelaney 我删除了 ping 的计数,而不是排序,我使用 grep 所以假设数据应该通过管道流向 grep,但它似乎永远运行而没有打印任何内容。
  • 您没有收到任何信息,因为输出与超时不匹配。试试 $python logsearch.py​​ | grep -v 超时

标签: python linux shell pipe subprocess


【解决方案1】:

为什么要使用 grep?为什么不用 Python 做所有的事情?

from subprocess import Popen, PIPE
p = Popen(['ping', 'google.com'], shell=False, stdin=PIPE, stdout=PIPE)

for line in p.stdout:
    if 'timeout' in line.split():
        # Process the error
        print("Timeout error!!")
    else:
        print(line)

更新:
我按照推荐的@triplee 更改了 Popen 行。 Actual meaning of 'shell=True' in subprocess 的优缺点

【讨论】:

  • 之所以需要 grep 或其他 shell cmd 是为了增加灵活性,有时我们可能需要添加 grep 或 sort 或 awk 以便更好地处理数据。
  • 好的。以防万一,您可以使用Python module sh。实现了很多 bash 有用的命令。
  • 同时使用Popen(['ping', 'google.com'], shell=False, ...) 来避免产生无用的shell。
猜你喜欢
  • 2012-03-21
  • 1970-01-01
  • 2012-05-11
  • 2013-12-15
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
相关资源
最近更新 更多