将控制台输出重定向到Python字符串

时间:2009-06-15 07:43:13

标签: python bash

  

可能重复:
  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')

UPD Here是一个相关主题。

1 个答案:

答案 0 :(得分:16)

使用subprocess模块。

from subprocess import Popen, PIPE

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