将输出命令重定向到变量或文件?

Rob*_* IV 2 python command-line output

我正在尝试编写一个python脚本,它允许我从命令中获取输出并将其放入文件或变量(Preferability a variable).

在我的代码中,我已将输出重定向到StringIO()对象.从那里,我想要输出一个命令并将其放入该StringIO()对象.

以下是我的代码示例:

from StringIO import StringIO
import sys

old_stdout = sys.stdout

result = StringIO()
sys.stdout = result

# This will output to the screen, and not to the variable
# I want this to output to the 'result' variable
os.system('ls -l')
Run Code Online (Sandbox Code Playgroud)

另外,我如何获取结果并将其放入字符串?

提前致谢!!

glg*_*lgl 5

import subprocess
sp = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
output, _ = sp.communicate()
print "Status:", sp.wait()
print "Output:"
print output
Run Code Online (Sandbox Code Playgroud)