我有一个python函数,它在终端上打印一些行。
以下是我如何执行功能:
python3 test.py
以下是文件中的一些代码:
column1 = "|=========="
column2 = "|==============================================================="
column3 = "|==================================="
column4 = "|======================="
print("n"+column1+column2+column3+column4+"|")
print("|SCRIPT ID |SCRIPT NAME |Start Time |RUN ID |")
print(column1+column2+column3+column4+"|")
它在终端中打印以下内容:
|==========|===============================================================|===================================|=======================|
|SCRIPT ID |SCRIPT NAME |Start Time | RUN ID |
|==========|===============================================================|===================================|=======================|
|1 |TEST_SCRIPT |2020-04-17 11:46:28.054074+05:30 |201 |
|==========|===============================================================|===================================|=======================|
Entering - SCRIPT
Verification Started
Verification Completed in 0 Hours 00 Min 00.000602 sec
Methods Execution Started
Methods Execution Completed
EXITING - SCRIPT
我想在日志文件中维护函数的输出。因此,如果我运行python3 test.py
,它应该在名为logs
的文件夹中创建一个名为test.py-202004171148.log
的文件,将所有输出存储在该文件中。
我该怎么做?
使用日期时间保存文件:
import datetime
file = open(str(datetime.now().strftime('test.py-%Y%m%d%H%M%S.log')), "w")
file.write("yourlogs")
file.close()
保存您可以使用的文件:
import datetime
file = open("test.py-"+str(datetime.datetime.now().timestamp())+".log", "w")
file.write("yourlogs")
file.close()
将这几行代码添加到脚本顶部应该会将所有输出重定向到控制台并写入文件
import sys
import datetime
class Printer(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for file in self.files:
file.write(obj)
file.flush()
def flush(self):
for file in self.files:
file.flush()
f = open(f"{__file__}-{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.log", 'w')
sys.stdout = Printer(sys.stdout, f)
#Your print statements below
print("Hello world!")
您可以使用日志记录模块。根据所需的日志级别,您必须将print()
替换为logging.info()
、logging.warning()
或logging.error()
。
import logging
from datetime import datetime
fn = datetime.now().strftime('logs/test.py-%Y%m%d%H%M%S.log')
logging.basicConfig(filename=fn, level=logging.INFO)
logging.info('Entering - SCRIPT')
logging.info('etc...')
默认格式将在每条消息前面加上日志级别和记录器名称。如果你不想这样,你可以用format
覆盖它。
logging.basicConfig(filename=fn, level=logging.INFO, format='%(message)s')