【问题标题】:Redirect an output command to a variable or file?将输出命令重定向到变量或文件?
【发布时间】:2012-11-20 15:33:23
【问题描述】:

我正在尝试编写一个 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')

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

提前致谢!!

【问题讨论】:

标签: python command-line output


【解决方案1】:
import subprocess
sp = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
output, _ = sp.communicate()
print "Status:", sp.wait()
print "Output:"
print output

【讨论】:

  • 在我的真实代码中,我没有使用ls -l。我正在使用命令find *。当我在评论中使用find * 代替您在评论中的代码中的ls -l 时,它没有给出任何东西,但是当我转到正常命令行时,它输出一切正常。当我使用ls -l 时,它工作正常。建议?
  • 您可以使用Popen() 参数shell=True 并给它一个要执行的字符串。或者你可以使用['find', '.'],它应该基本上是相同的,或多或少。
猜你喜欢
  • 1970-01-01
  • 2018-06-07
  • 2012-03-01
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 2012-05-06
  • 2012-07-05
  • 2011-12-15
相关资源
最近更新 更多