我正在尝试编写一个python脚本,它将允许我从命令中获取输出并将其放入文件或变量(首选变量)。
在我的代码中,我将输出重定向到一个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')

另外,我如何获取结果并将其放入字符串中?
提前谢谢!!

最佳答案

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

关于python - 将输出命令重定向到变量或文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13476590/

10-16 22:08