【问题标题】:redirecting python output to a log file将python输出重定向到日志文件
【发布时间】:2016-10-07 18:23:04
【问题描述】:

我有一个简单的要求。我有一个带有变量列表的 python 文件。我想执行 python 文件并将其输出写入日志文件。这样做的简单方法是什么? 例子: var.py 有如下代码

x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
z = datetime.datatime.today().strftime('%Y-%m-%d')

我希望日志以相同的顺序显示变量解析

x = (10,11,12)
y = 'case when id =1 then gr8 else ok end'
z = 2016-06-07

如何在 python 中完成此操作?

这是我尝试过的

# In:
import logging

# set root logger level
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)

# setup custom logger
logger = logging.getLogger(__name__)
handler = logging.FileHandler('example.log')
handler.setLevel(logging.INFO)
logger.addHandler(handler)

# log
x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
logger.debug(x)
logger.debug(y)

example.log 文件为空

【问题讨论】:

  • 没有一个明确的方法可以做到这一点,但你可以使用 Python 的内置日志模块来进行一些操作

标签: python variables output


【解决方案1】:

Input/Output Operations 使用 Python 很容易。

您可以手动打开、写入和关闭文件,即:

text_file = open("OutputFile.txt", "w")
text_file.write("Write blablabla into a file")
text_file.close()

或者您使用上下文管理器(文件会自动为您关闭),即:

这通常是一种更好的编码习惯..

with open("Output.txt", "w") as text_file:
    text_file.write("Write blablabla into a file")

在你的例子中:

import datetime

x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
z = datetime.datetime.today().strftime('%Y-%m-%d')

outfile = 'outputfile.txt'

with open(outfile, 'w') as f:
    f.write(str(x))
    f.write("\n")
    f.write(y)
    f.write("\n")
    f.write(z)
    f.write("\n")

在脚本文件夹中生成一个名为 outputfile.txt 的文件,其中包含以下几行:

(10, 11, 12)
case when id =1 then gr8 else ok end
2016-06-07

但是如果你想要一个特定的日志库,你可以看看LOGGING

import datetime, logging

logfile = 'logfile.log'

logging.basicConfig(filename=logfile, 
                    level=logging.INFO,
                    format='%(asctime)s.%(msecs)03d %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
z = datetime.datetime.today().strftime('%Y-%m-%d')

logging.info(x)
logging.info(y)
logging.info(z)

这将产生以下输出:

2016-06-07 15:28:12.874 INFO (10, 11, 12)
2016-06-07 15:28:12.874 INFO case when id =1 then gr8 else ok end
2016-06-07 15:28:12.874 INFO 2016-06-07

【讨论】:

  • 在 IPython 中试过这段代码。我在我的 python 文件夹中没有看到 log file.log 文件?是否有任何特定的添加,例如我需要添加的处理程序来制作日志文件?谢谢
【解决方案2】:

使用 python 记录器功能

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
logging.debug(x)
logging.debug(y)

【讨论】:

  • 我希望输出也包含变量名。例如 z=2016-06-07
  • 操作对象。在字符串对象之前假装字符串。
  • logging.debug("x=" + str(x))
  • 我尝试了以下代码。但我看到 example.log 是空的
  • 我不完全了解日志记录模型。但我看到的是,当我从 IPython 笔记本执行时,我在文件夹中看到了日志文件,但它是空的。我看到创建了记录器对象,但不确定实际的日志文件。你可以在 IPython 中试试这个吗?
猜你喜欢
  • 1970-01-01
  • 2020-10-14
  • 2021-06-27
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
  • 2010-09-18
相关资源
最近更新 更多