Python 如何将 pprint 模块的输出发送到日志文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3880399/
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-18 13:09:54 来源:igfitidea点击:
how to send the output of pprint module to a log file
提问by AKM
I have the following code:
我有以下代码:
logFile=open('c:\temp\mylogfile'+'.txt', 'w')
pprint.pprint(dataobject)
how can i send the contents of dataobject to the log file on the pretty print format ?
如何以漂亮的打印格式将数据对象的内容发送到日志文件?
采纳答案by livibetter
回答by ddalex
Please use pprint.pformat, which returns a formated string that can be dumped directly to file.
请使用pprint.pformat,它返回可以直接转储到文件的格式化字符串。
>>> import pprint
>>> with open("file_out.txt", "w") as fout:
... fout.write(pprint.pformat(vars(pprint)))
...
Reference:
参考:
回答by Kaiwen Sun
For Python 2.7
对于 Python 2.7
logFile = open('c:\temp\mylogfile'+'.txt', 'w')
pp = pprint.PrettyPrinter(indent=4, stream=logFile)
pp.pprint(dataobject) #you can reuse this pp.print

