Python 如何将终端的输出写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23364096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:50:20  来源:igfitidea点击:

How to write output of terminal to file

python

提问by qwerty12345

I want to save result of script to file. Example of script:

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

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

And I want to save to file print value. I know that I can do that in script f=open()..., but I want to do that using output in terminal. I read that I can use module subprocessbut I don't know it is correct.

我想保存到文件打印值。我知道我可以在 script 中做到这一点f=open()...,但我想在终端中使用输出来做到这一点。我读到我可以使用模块,subprocess但我不知道它是正确的。

采纳答案by luk32

IMO this is the correct pythonic way, with-out relying on the system shell:

IMO 这是正确的 pythonic 方式,不依赖于系统外壳:

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

In python you can change what is the default stdoutobject. You just need to assign whatever you want to sys.stdout. I think the object just need to have a writemethod defined (not absolutely sure, though).

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

This would do:

这会做:

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

It's essentially the same what 0605002suggests for systems that support syntax he uses, but realized in pure python and should be more portable.

它与0605002为支持他使用的语法的系统所建议的基本相同,但在纯 python 中实现并且应该更便携。

Even more pythonic way, as per comment suggestion:

更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

Of course you can refactor your "client code" and make it a function or something.

当然,您可以重构“客户端代码”并使其成为函数或其他东西。

回答by 0605002

You can redirect the output to a file using >in terminal:

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

python your_script.py > output.txt

回答by mhaghighat

python file.py &> out.txt

This will direct all the output including the errors to the out.txt.

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