使用时间戳将文本附加到文本文件

时间:2016-11-11 08:28:37

标签: python terminal

我想将python代码的输出附加到文本文件中。上面是我的python代码,我每2小时循环一次

if response == 0:
print(hostname, "is up")

if option == 1:
   print(option, "is the option')
   print('this is option number 1')
elif option == 2:
   print(option, "is the option')
   print('this is option number 2')
else:
   print(option, "is the other option')
   print('this is the result of other option')

我注意到我需要以下代码将结果附加到文本文件中。

with open("test.txt", "a") as myfile:
myfile.write("appended text")

如何将每个输出记录到文本文件中并包含时间戳?例如

09:10  192.168.0.1 is up
09:10  1 is the option
09:11  this is option number 1
11:15  192.168.0.1 is up
11:10  1 is the option
11:11  this is option number 1
13:10  192.168.0.1 is up
13:10  3 is the other option
13:11  this is the result of other option

1 个答案:

答案 0 :(得分:0)

Python确实有一个你可以使用的日志库,但如果你想自己创建,那么你可以采取以下方法。

这里有两个函数write_log(),它们使用您正在使用的参数并创建一些日志条目。然后,此函数调用write_logline()将每个部分写入屏幕(可选)以及包含时间戳的文件:

from datetime import datetime

def write_logline(logfile, text):
    now = datetime.strftime(datetime.now(), '%H:%M')
    log_text = '{}  {}\n'.format(now, text)
    print(log_text, end='')     # also display log info, comment out if not needed
    logfile.write(log_text)


def write_log(response, hostname, option):

    with open("test.txt", "a") as logfile:
        if response == 0:
            write_logline(logfile, '{} is up'.format(hostname))

        if option == 1:
           write_logline(logfile, '{} is the option'.format(option))
           write_logline(logfile, 'this is option number 1')
        elif option == 2:
           write_logline(logfile, '{} is the option'.format(option))
           write_logline(logfile, 'this is option number 2')
        else:
           write_logline(logfile, '{} is the other option'.format(option))
           write_logline(logfile, 'this is the result of other option')

write_log(0, '192.168.0.1', 1)   
write_log(0, '192.168.0.1', 1)   
write_log(0, '192.168.0.1', 3)   

作为替代方案,您可以考虑将日志记录功能编写为Python类。这样可以节省您跟踪文件句柄的时间,并允许您使用Python的with语句:

class LogTimestamp:

    def __init__(self, log_filename):
        self.log_filehandle = open(log_filename, 'a')

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.log_filehandle.close()               

    def write_logline(self, text):
        now = datetime.strftime(datetime.now(), '%H:%M')
        log_text = '{}  {}\n'.format(now, text)
        print(log_text, end='')     # also display log info, comment out if not needed
        self.log_filehandle.write(log_text)

    def write(self, response, hostname, option):
        if response == 0:
            self.write_logline('{} is up'.format(hostname))

        if option == 1:
           self.write_logline('{} is the option'.format(option))
           self.write_logline('this is option number 1')
        elif option == 2:
           self.write_logline('{} is the option'.format(option))
           self.write_logline('this is option number 2')
        else:
           self.write_logline('{} is the other option'.format(option))
           self.write_logline('this is the result of other option')


# Write 3 entries to the log

with LogTimestamp('test.txt') as log:
    log.write(0, '192.168.0.1', 1)   
    log.write(0, '192.168.0.1', 2)   
    log.write(0, '192.168.0.1', 3)   

两个版本都会为您提供如下输出文件:

09:51  192.168.0.1 is up
09:51  1 is the option
09:51  this is option number 1
09:51  192.168.0.1 is up
09:51  2 is the option
09:51  this is option number 2
09:51  192.168.0.1 is up
09:51  3 is the other option
09:51  this is the result of other option