【问题标题】:Capture the result from the terminal (external process)从终端捕获结果(外部进程)
【发布时间】:2013-08-19 12:06:31
【问题描述】:

我需要从终端获取结果

mask = "audio"
a = os.system("ls -l | grep %s | awk '{ print $9 }'" % mask)
print a # a = 0, that's the exit code

#=>
file1_audio
file2_audio
0

这个命令只是将结果打印到控制台,而我想将它捕获到一个变量中。

【问题讨论】:

  • 您在这里尝试做的事情也可以在纯 Python 中完成。
  • @Keith,这只是一个例子,我有更严肃的任务。
  • 然后您可以使用subprocess 模块运行管道并读取标准输出。
  • 请阅读常见问题解答。如果可能的话,您应该在您的问题中提出这一点。此外,这是一个常见问题,并且已经有很多答案。
  • 请注意,如果您只是浏览the docs for os.system,他们会建议您改用subprocess,并将您直接链接到a section that shows exactly what you're trying to do。我不知道您为什么希望我们能够比文档更好地解释它。

标签: python linux python-2.7 terminal


【解决方案1】:

使用subprocess 模块

import subprocess

p = subprocess.Popen("ls -l | grep %s | awk '{ print $9 }'" % mask, 
    shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

shell=True 是必需的,因为管道由 shell 运行,否则您会得到 No such file or directory

在 Python 2.7 中你也可以使用

output = subprocess.check_output(
    "ls -l | grep %s | awk '{ print $9 }'" % mask
    stderr=subprocess.STDOUT,
    shell=True)

但是我发现使用起来很麻烦,因为如果管道返回的退出代码不是 0,它会抛出 subprocess.CalledProcessError,并且要捕获 stdout 和 stderr,您需要将它们交错,这使得它在许多情况下无法使用。

【讨论】:

  • 有没有办法将结果作为数组或列表而不是字符串?
  • 你有一个字符串,还不够好吗? stdout,stderr 是字节流,而不是列表。如果您需要一个列表,例如使用 stdout.splitlines()
  • 他这里只需要check_output;没有理由创建 Popen 并调用 communicate 除非您也有输入发送它(或需要在创建和通信之间做其他事情等)。
  • 确实,如果他有 2.7。我总是忘记这一点,因为我发现它使用起来很麻烦,在非零退出时抛出异常等等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多