Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文本附加到带有时间戳的文本文件_Python_Datetime_Terminal - Fatal编程技术网

Python 将文本附加到带有时间戳的文本文件

Python 将文本附加到带有时间戳的文本文件,python,datetime,terminal,Python,Datetime,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 opt

我想将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

Python确实有一个日志库,您可以使用它,但是如果您希望创建自己的日志库,那么您可以采用以下方法

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

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

Python确实有一个日志库,您可以使用它,但是如果您希望创建自己的日志库,那么您可以采用以下方法

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

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

如果你经常这样做,那么值得你去学习和使用。如果你经常这样做,那么值得你去学习和使用。