【问题标题】:redirecting screen output from python logging to a file将屏幕输出从 python 日志重定向到文件
【发布时间】:2021-06-27 19:55:01
【问题描述】:

如何在运行时使用重定向将 python 日志记录语句的输出重定向到文件?

我在 Debian 中使用 python 3.7。当我将包含打印语句的 python 脚本的输出重定向到一个文件时,我得到了预期的结果 - 一个包含输出的文件。

如果我使用 logging.debug 创建屏幕输出并将其重定向到一个文件,我会在屏幕上显示输出和一个零大小的文件。

python_test.py

print('hello')
python python_test.py > test.txt
more test.txt
hello

python_logging_test.py

import logging

logging.basicConfig(level=logging.DEBUG, format='%(message)s')

logging.debug('from logger')
python python_logging_test.py > test2.txt
from logger
ls -al test2.txt
-rw-r--r-- 1 bart bart 0 Mar 31 20:00 test2.txt

【问题讨论】:

    标签: python bash redirect


    【解决方案1】:

    日志记录不使用标准输出流,它使用标准错误输出流。

    重定向标准错误流:

    方法一

    python python_logging_test.py 2> test2.txt
    
    more test2.txt
    from logging
    

    方法2

    使用标准缓冲区:

    stdbuf -e L python python_logging_test.py > test2.txt
    
    more test2.txt
    from logger
    

    来自 stdbuf --help -e, --error=MODE 调整标准错误流缓冲 如果 MODE 为 'L',则相应的流将被行缓冲。

    【讨论】:

      猜你喜欢
      • 2016-10-07
      • 2023-04-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多