如何将终端输出写入文件

qwe*_*345 7 python

我想将脚本的结果保存到文件中.脚本示例:

#!/usr/bin/env python
i=0
while i<10:
  a=raw_input('Write a number')
  print 'Result%s'%str(2*a)
  i+=1
Run Code Online (Sandbox Code Playgroud)

我想保存到文件打印值.我知道我可以在脚本中执行此操作f=open()...,但我想使用终端中的输出来执行此操作.我读到我可以使用模块,subprocess但我不知道它是正确的.

luk*_*k32 12

IMO这是正确的pythonic方式,没有依赖系统shell:

import sys
f = open("test.out", 'w')
sys.stdout = f
print "test"
f.close()
Run Code Online (Sandbox Code Playgroud)

在python中,您可以更改默认stdout对象.你只需要分配你想要的任何东西sys.stdout.我认为对象只需要write定义一个方法(但不是绝对确定).

这样做:

import sys
f = open("test.out", 'w')
sys.stdout = f

i=0
while i<10:
  a=raw_input('Write a number')
  print 'Result%s'%str(2*a)
  i+=1

f.close()
Run Code Online (Sandbox Code Playgroud)

它基本上与0605002为支持他使用的语法的系统所建议的相同,但是在纯python中实现并且应该更加可移植.

更多的pythonic方式,根据评论建议:

import sys

with open("test.out", 'w') as f:
  sys.stdout = f

  i=0
  while i<10:
    a=raw_input('Write a number')
    print 'Result%s'%str(2*a)
    i+=1
Run Code Online (Sandbox Code Playgroud)

当然,您可以重构您的"客户端代码"并使其成为一种功能.


mha*_*hat 10

python file.py &> out.txt
Run Code Online (Sandbox Code Playgroud)

这会将包括错误在内的所有输出定向到 out.txt。

  • 太棒了。很多答案都忽略了这一点 (2认同)
  • &amp;&gt; 也包含错误,但 &gt; 不包含。 (2认同)

060*_*002 9

您可以使用>终端将输出重定向到文件:

python your_script.py > output.txt
Run Code Online (Sandbox Code Playgroud)