Redirect an output command to a variable or file?

喜夏-厌秋 提交于 2019-12-11 02:30:27

问题


I'm trying to write a python script that will allow me to take the output from a command and to put that into a file or variable (Preferability a variable).

In my code, I have redirected the output to a StringIO() object. From that, I want take the output a command and to put it into that StringIO() object.

Here is a sample of my code:

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')

Also, how do I take result and put it into a string?

Thanks in advance!!


回答1:


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


来源:https://stackoverflow.com/questions/13476590/redirect-an-output-command-to-a-variable-or-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!