开发者社区> 问答> 正文

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

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

问题来源于python学习网

展开
收起
保持可爱mmm 2019-12-11 16:53:44 1977 0
2 条回答
写回答
取消 提交回答
  • python有自带的logging模块, 按照文档配置使用就可以了 https://docs.python.org/zh-cn/3/howto/logging.html

    2020-03-19 19:43:01
    赞同 展开评论 打赏
  • 首先导入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学习网

    2019-12-11 16:53:53
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
PostgresChina2018_赖思超_PostgreSQL10_hash索引的WAL日志修改版final 立即下载
Kubernetes下日志实时采集、存储与计算实践 立即下载
日志数据采集与分析对接 立即下载