开发者

how to send the output of pprint module to a log file

I have the following code:

logFile=open('c:\\temp\\mylogfile'+'.txt', 'w')
pprint.pprint(dataobject)

how can i send the contents of data开发者_开发百科object to the log file on the pretty print format ?


with open("yourlogfile.log", "w") as log_file:
    pprint.pprint(dataobject, log_file)

See the documentation.


Please use pprint.pformat, which returns a formated string that can be dumped directly to file.

>>> import pprint
>>> with open("file_out.txt", "w") as fout:
...     fout.write(pprint.pformat(vars(pprint)))
... 

Reference:

http://docs.python.org/2/library/pprint.html


For 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜