抓住终端的输出

时间:2013-08-16 04:55:57

标签: python linux python-2.7 terminal ubuntu-12.04

我需要在终端中运行一个proccess来获取它的输出。

import subprocess
subprocess.check_output(["my_util", "some_file.txt", " | grep 'Some data1' | awk '{print $2}'"])

#or
subprocess.check_output(["my_util", "full_path/some_file.txt", "| grep 'Some data1'", "| awk '{print $2}'"])

在REPL中没有任何反应,而在终端中手动运行它会给我正确的输出。

更新

sublime text的输出:

my_util FAIL formats: can't open input pipe `| grep 'Sample data1'': premature EOF
my_util FAIL formats: can't open input pipe `| awk '{print $2}'': premature EOF
Traceback (most recent call last):
  File "/test1.py", line 4, in <module>
    "| grep 'Sample data1'", "| awk '{print $2}'"])
  File "/usr/lib/python2.7/subprocess.py", line 544, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '["my_util", "full_path/some_file.txt", "| grep 'Some data1'", "| awk '{print $2}'"]' returned non-zero exit status 2

2 个答案:

答案 0 :(得分:1)

可以使用os.system代替子进程

import os

os.system("my_util some_file.txt | grep 'Some data1' | awk '{print $2}'" )

答案 1 :(得分:0)

我认为你不能在子进程中管道这样的命令。

Here's a question,其答案描述了如何使用子流程执行管道命令。

Here's another description如何做到这一点。