如何将python屏幕输出保存到文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25023233/
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
How to save python screen output to a text file
提问by Ironfist
I'm new to Python. I need to query items from a dict and save the result to a text file. Here's what I have:
我是 Python 的新手。我需要从字典中查询项目并将结果保存到文本文件中。这是我所拥有的:
import json
import exec.fullog as e
input = e.getdata() #input now is a dict() which has items, keys and values.
#Query
print 'Data collected on:', input['header']['timestamp'].date()
print '\n CLASS 1 INFO\n'
for item in input['Demographics']:
if item['name'] in ['Carly', 'Jane']:
print item['name'], 'Height:', item['ht'], 'Age:', item['years']
for item in input['Activity']:
if item['name'] in ['Cycle', 'Run', 'Swim']:
print item['name'], 'Athlete:', item['athl_name'], 'Age:', item['years']
How do I save the printed output to a text file?
如何将打印输出保存到文本文件?
采纳答案by Boris Gorelik
Let me summarize all the answers and add some more.
让我总结一下所有的答案并补充一些。
To write to a file from within your script, user file I/O toolsthat are provided by Python (this is the
f=open('file.txt', 'w')stuff.If don't want to modify your program, you can use stream redirection (both on windowsand on Unix-like systems). This is the
python myscript > output.txtstuff.If you want to see the output bothon your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command(windows version also exists, but I have never used it)
- Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module. The learning curve here is the steepest among all the options, but in the long run it will pay for itself.
要从脚本中写入文件,请使用Python 提供的用户文件 I/O 工具(这就是
f=open('file.txt', 'w')东西。如果不想修改您的程序,您可以使用流重定向(在Windows和类 Unix 系统上)。这就是
python myscript > output.txt东西。如果你想看到的输出都在屏幕上,并在日志文件中,如果你的系统是Unix,你不想修改你的程序,你可以使用tee命令(Windows版本也存在,但我有没用过)
- 将所需输出发送到屏幕、文件、电子邮件、推特的更好方法,无论使用日志记录模块。这里的学习曲线是所有选项中最陡峭的,但从长远来看,它会物有所值。
回答by abarnert
What you're asking for isn't impossible, but it's probably not what you actually want.
您所要求的并非不可能,但可能不是您真正想要的。
Instead of trying to save the screen output to a file, just write the output to a file instead of to the screen.
不要尝试将屏幕输出保存到文件,只需将输出写入文件而不是屏幕。
Like this:
像这样:
with open('outfile.txt', 'w') as outfile:
print >>outfile, 'Data collected on:', input['header']['timestamp'].date()
Just add that >>outfileinto all your print statements, and make sure everything is indented under that withstatement.
只需将其添加>>outfile到所有打印语句中,并确保所有内容都在该with语句下缩进。
More generally, it's better to use string formatting rather than magic printcommas, which means you can use the writefunction instead. For example:
更一般地,最好使用字符串格式而不是魔术print逗号,这意味着您可以使用该write函数。例如:
outfile.write('Data collected on: {}'.format(input['header']['timestamp'].date()))
But if printis already doing what you want as far as formatting goes, you can stick with it for now.
但是,如果print就格式化而言已经在做你想做的事,你现在可以坚持下去。
What if you've got some Python script someone else wrote (or, worse, a compiled C program that you don't have the source to) and can't make this change? Then the answer is to wrap it in another script that captures its output, with the subprocessmodule. Again, you probably don't want that, but if you do:
如果您有一些其他人编写的 Python 脚本(或者更糟的是,您没有源代码的已编译 C 程序)并且无法进行此更改怎么办?然后答案是将其包装在另一个脚本中,该脚本使用subprocess模块捕获其输出。同样,您可能不希望那样,但如果您这样做:
output = subprocess.check_output([sys.executable, './otherscript.py'])
with open('outfile.txt', 'wb') as outfile:
outfile.write(output)
回答by apsdehal
You would probably want this. Simplest solution would be
你可能想要这个。最简单的解决方案是
Create file first.
首先创建文件。
open file via
通过打开文件
f = open('<filename>', 'w')
or
或者
f = open('<filename>', 'a')
in case you want to append to file
如果您想附加到文件
Now, write to the same file via
现在,通过写入同一个文件
f.write(<text to be written>)
Close the file after you are done using it
使用完毕后关闭文件
#good pracitice
f.close()
回答by metaperture
abarnert's answer is very good and pythonic. Another completely different route (not in python) is to let bash do this for you:
abarnert's answer非常好,pythonic。另一个完全不同的路线(不在 python 中)是让 bash 为你做这件事:
$ python myscript.py > myoutput.txt
This works in general to put all the output of a cli program (python, perl, php, java, binary, or whatever) into a file, see How to save entire output of bash script to filefor more.
这通常适用于将 cli 程序(python、perl、php、java、二进制或其他)的所有输出放入一个文件中,有关更多信息,请参阅如何将 bash 脚本的整个输出保存到文件中。
回答by ZZZ
A quick and dirty hack to do this within the scriptis to direct the screen output to a file:
在脚本中执行此操作的一个快速而肮脏的技巧是将屏幕输出定向到一个文件:
import sys
stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")
and then reverting back to outputting to screen at the end of your code:
然后在代码结束时恢复到输出到屏幕:
sys.stdout.close()
sys.stdout=stdoutOrigin
This should work for a simple code, but for a complex code there are other more formal ways of doing it such as using Python logging.
这应该适用于简单的代码,但对于复杂的代码,还有其他更正式的方法,例如使用Python logging。
回答by Matt W
Here's a really simple way in python 3+:
这是python 3+中一个非常简单的方法:
f = open('filename.txt', 'w')
print('something', file = f)
^ found that from this answer: https://stackoverflow.com/a/4110906/6794367
^ 从这个答案中发现:https: //stackoverflow.com/a/4110906/6794367
回答by Ravi G
python script_name.py > saveit.txt
Because this scheme uses shell command lines to start Python programs, all the usual shell syntax applies. For instance, By this, we can route the printed output of a Python script to a file to save it.
因为这个方案使用 shell 命令行来启动 Python 程序,所以所有常用的 shell 语法都适用。例如,通过这个,我们可以将一个 Python 脚本的打印输出路由到一个文件来保存它。
回答by Omar Baltaji
I found a quick way for this:
我找到了一个快速的方法:
log = open("log.txt", 'a')
def oprint(message):
print(message)
global log
log.write(message)
return()
code ...
log.close()
Whenever you want to print something just use oprint rather than print.
每当您想打印某些内容时,只需使用 oprint 而不是打印。
Note1: In case you want to put the function oprint in a module then import it, use:
注意1:如果您想将函数 oprint 放在模块中然后导入它,请使用:
import builtins
builtins.log = open("log.txt", 'a')
Note2: what you pass to oprint should be a one string (so if you were using a comma in your print to separate multiple strings, you may replace it with +)
注意2:你传递给 oprint 的应该是一个字符串(所以如果你在打印中使用逗号来分隔多个字符串,你可以用 + 替换它)

