【问题标题】:Redirecting console output to a Python string [duplicate]将控制台输出重定向到 Python 字符串 [重复]
【发布时间】:2009-06-15 07:43:13
【问题描述】:

可能重复:
How can I capture the stdout output of a child process?

我正在从 Python 的 bash 中运行类似 cat 的程序:

   import os

   os.system('cat foo.txt')

如何在 Python 脚本中获取 shell 命令的输出,例如:

   s = somefunction('cat foo.txt')

?

UPDHere 是相关线程。

【问题讨论】:

标签: python bash


【解决方案1】:

使用subprocess 模块。

from subprocess import Popen, PIPE

(stdout, stderr) = Popen(["cat","foo.txt"], stdout=PIPE).communicate()
print stdout

【讨论】:

    猜你喜欢
    • 2012-02-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多