我有一个简单的请求。我有一个包含变量列表的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文件为空
答案 0 :(得分:1)
您可以手动打开,写入和关闭文件,即:
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
答案 1 :(得分:0)
使用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)