ITPub博客

首页 > IT职业 > IT生活 > python怎么将打印输出日志文件

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

IT生活 作者:longmanma 时间:2021-09-11 10:28:41 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平台,欢迎关注!

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2730/viewspace-2835766/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: shell变量介绍
请登录后发表评论 登录
全部评论

注册时间:2019-12-18

  • 博文量
    492
  • 访问量
    11985