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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/994902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:58:23  来源:igfitidea点击:

Redirecting console output to a Python string

pythonbash

提问by Alex

Possible Duplicate:
How can I capture the stdout output of a child process?

可能的重复:
如何捕获子进程的 stdout 输出?

I'm running a cat-like program in bash from Python:

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

   import os

   os.system('cat foo.txt')

How do I get the output of the shell command back in the Python script, something like:

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

   s = somefunction('cat foo.txt')

?

?

UPD: Hereis a related thread.

UPD是一个相关的线程。

回答by ismail

Use the subprocessmodule.

使用子流程模块。

from subprocess import Popen, PIPE

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