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

4 投票
1 回答
15439 浏览
提问于 2025-04-15 12:15

可能重复的问题:
我该如何获取子进程的标准输出?

我在Python中通过bash运行一个类似于cat的程序:

   import os

   os.system('cat foo.txt')

我该如何在Python脚本中获取这个shell命令的输出,类似于:

   s = somefunction('cat foo.txt')

?

更新: 这里

1 个回答

16

使用 subprocess 模块。

from subprocess import Popen, PIPE

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

撰写回答