【问题标题】:python 2.3 how to run a piped commandpython 2.3 如何运行管道命令
【发布时间】:2012-07-28 01:16:53
【问题描述】:

我想运行这样的命令

grep -w 1 pattern <(tail -f mylogfile.log)

基本上从 python 脚本中,我想监视特定字符串的日志文件,并在发现后立即继续使用 python 脚本。
我正在使用os.system(),但这是挂起的。 bash 中的相同命令效果很好。

我有一个非常旧的python版本(v2.3),所以没有子流程模块。

我们有办法实现这一点

【问题讨论】:

  • 您可以尝试commands 模块,但至少应该有一个人给出简单的答案——升级到更新版本的python ;)
  • 想必他在升级 python 时遇到了与拉subprocess.py from SVN 相同的问题

标签: python python-2.3


【解决方案1】:

如果我理解正确,您想像这样将输出发送到 python -

tail -f mylogfile.log | grep -w 1 pattern | python yourscript.py

即读取日志文件的所有更新,并将匹配的行发送到您的脚本。

要从标准输入读取,您可以使用类似文件的对象:sys.stdin。

所以你的脚本看起来像

import sys

for line in sys.stdin.readlines():
    #process each line here.

【讨论】:

    【解决方案2】:

    首先,我认为你应该使用的命令是grep -w -m 1 'pattern' &lt;(tail -f in)

    要在 python 中执行命令,请使用子进程模块中的 Popen 构造函数。阅读更多 http://docs.python.org/library/subprocess.html

    【讨论】:

      【解决方案3】:

      在 Python 2.3 中,需要使用subprocess from SVN

      import subprocess
      import shlex
      subprocess.call(shlex.split("/bin/bash -c 'grep -w 1 pattern <(tail -f mylogfile.log)'"))
      

      明确地说,您需要从上面的 SVN 链接安装它。

      由于您使用的 shell 重定向,您需要使用 /bin/bash -c 调用它


      编辑

      如果您想使用os.system() 解决此问题,只需将命令包装在/bin/bash -c 中,因为您使用的是shell 重定向...

      os.system("/bin/bash -c 'grep -w 1 pattern <(tail -f mylogfile.log)'")
      

      【讨论】:

      • 再一次,我没有子进程,无法在我当前的环境中下载任何新模块:-(
      • 无法下载是新信息,很高兴知道...虽然我想知道将subprocess.py 复制到vi 中的文件中有多难,因为您是大概是通过ssh 访问
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      相关资源
      最近更新 更多