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

4
我正在从Python中运行一个类似于cat的程序来执行bash命令:

可能是重复问题:
如何捕获子进程的标准输出?

   import os

   os.system('cat foo.txt')

如何在Python脚本中获取shell命令的输出,类似于以下内容:

   s = somefunction('cat foo.txt')

?

UPD: Here is a related thread.


重复的...... https://dev59.com/G3NA5IYBdhLWcg3wh-cC#923108 - Paolo Bergantino
1个回答

16

使用subprocess模块。

from subprocess import Popen, PIPE

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接