将输出命令重定向到变量或文件? [英] Redirect an output command to a variable or file?
本文介绍了将输出命令重定向到变量或文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想写一个python脚本,这将允许我从一个命令的输出,并把它放入一个文件或变量(优选一个变量)。
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).
在我的代码中,我已经将输出重定向到 StringIO()
对象。从这里,我想要输出一个命令,并把它放入 StringIO()
对象。
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.
是我的代码示例:
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')
$
此外,如何获取结果并将其放入字符串中?
Thanks in advance!!
推荐答案
import subprocess
sp = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
output, _ = sp.communicate()
print "Status:", sp.wait()
print "Output:"
print output
这篇关于将输出命令重定向到变量或文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文