品易云推流 关闭
文章详情页
文章 > Python常见问题 > python怎么将打印输出日志文件

python怎么将打印输出日志文件

头像

爱喝马黛茶的安东尼

2019-11-04 09:26:512988浏览 · 0收藏 · 0评论

首先导入sys模块,然后利用sys.stdout将print行导向到你定义的日志文件中,例如:

import sys
# make a copy of original stdout route
stdout_backup = sys.stdout
# define the log file that receives your log info
log_file = open("message.log", "w")
# redirect print output to log file
sys.stdout = log_file
print "Now all print info will be written to message.log"
# any command line that you will execute
...
log_file.close()
# restore the output to initial pattern
sys.stdout = stdout_backup
print "Now this will be presented on screen"

python学习网,免费的在线学习python平台,欢迎关注!

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图