Python 2.7-立即重定向到日志文件

时间:2019-02-12 13:24:47

标签: python-2.7 output flush

Python test.py脚本正在不停地收集数据。 要退出脚本,请按ctrl / c键。

脚本运行时文件test.log为空。 仅在脚本完成后才创建test.log的输出。

它正在Windows 2008服务器上运行。

如何“即时”保存输出,因此我可以检查test.log和 看到进度了吗?

from time import sleep
import sys

class Logger(object):
 def __init__(self, filename="Default.log"):
     self.terminal = sys.stdout
     self.log = open(filename, "a")

 def write(self, message):
     self.terminal.write(message)
     self.log.write(message)

def main():

 signaled_to_stop = False

 sheep_counter       = 1 

 sys.stdout = Logger("test.log")

 print "Running.. (press CTRL-C to stop)"

 while True:
     try:
         # Wait 3 seconds between each step.

         sleep(3)
         print "Counting sheeps... %s" % sheep_counter
         sheep_counter = sheep_counter + 1
         # If signaled to stop then - Create a peepfile and stop the loop
         if signaled_to_stop:

             print "Stop requested..."
             if signaled_to_stop:
                 break

     except KeyboardInterrupt:
         print "\nStopping (might take some seconds).."
         signaled_to_stop = True

     except SystemExit as err:
         raise err

 print "Process has finished."

# If this file is executed directly then call the main() method
if __name__ == "__main__":
 main()

输出就像:

python test.py

Running.. (press CTRL-C to stop)
Counting sheeps... 1
Counting sheeps... 2
Counting sheeps... 3

Stopping (might take some seconds)..
Counting sheeps... 4
Stop requested...
Process has finished.

2 个答案:

答案 0 :(得分:1)

您需要在系统上进行文件更新之前关闭文件。您无法阅读或阅读打开的文件。

def log(self, exampletext):
    with open(self.filename) as fn:
        fn.write(exampletext)

在此示例中,一旦写完该行,文件将自动关闭。

这就是我用来创建自己的日志文件的最终结果与您想要的相同的结果。

class Log: #class to write to log file with time stamps
def __init__(self):
    import os, traceback, time
    self.traceback = traceback
    self.os = os
    self.time = time
    if getattr(sys, 'frozen', False): #windows path fix
        self.exe = self.os.path.dirname(sys.executable)
    elif __file__:
        self.exe = self.os.path.dirname(__file__)
    if not os.path.exists(os.path.dirname(str(os.environ['USERPROFILE'])+"\\Documents\\AppName\\")):
        os.makedirs(str(os.environ['USERPROFILE'])+"\\Documents\\AppName\\")
    self.fname = str(os.environ['USERPROFILE'])+"\\Documents\\AppName\\debug.log"
    self.logfile = None
def error(self, error):
    exc_type, exc_obj, exc_tb = sys.exc_info()
    trace_stack = self.traceback.extract_tb(exc_tb)[-1]
    trace_format = "Error in file "+str(trace_stack[0])+"\r     on line "+str(trace_stack[1])+", from module '"+str(trace_stack[2])+"'\r        "+str(trace_stack[3])
    try:
        self.logfile = open(self.fname, "a+")
    except:
        self.logfile = open(self.fname, "w+")
    strtime = str(self.time.strftime("%d-%m-%Y,(%z),%H:%M:%S"))
    self.logfile.write("error: %s, %s, %s\r" %(strtime, error, trace_format))
    self.logfile.close()
    self.logfile = None
def log(self, log):
    try:
        self.logfile = open(self.fname, "a+")
    except:
        self.logfile = open(self.fname, "w+")
    strtime = str(self.time.strftime("%d-%m-%Y,(%z),%H:%M:%S"))
    self.logfile.write("log: %s, %s\r" %(strtime, log))
    self.logfile.close()
    self.logfile = None

这是我在应用程序中使用它的方式

try:
    self.log.log("This is a standard log")
except Exception as err:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    self.log.error("create_options failed\n%s, %s, %s, %s" %(err, exc_type, exc_obj, traceback.print_tb(exc_tb)))

编辑: 对于更快(简单)的日志,这是我的操作方法。

#logger.py
class log:
    def __init__(self, message):
        f = open("default.log", "a+")
        f.write(message+"\r")
        f.close()

#maincode.py
from logger import log
for i in range(10):
    log("Hello World %s" %i)

您可以简单地将所有打印语句替换为日志语句。

答案 1 :(得分:0)

解决方案是使用sys.stdout.flush()。 它“实时”更新日志文件。

我可以使用“>”

重定向输出
python test.py > result.log

test.py

from time import sleep
import sys

signaled_to_stop = False

sheep_counter       = 1 

print "Running.. (press CTRL-C to stop)"

while True:
    try:
        # Wait 3 seconds between each step.

        sleep(3)
        print "Counting sheeps... %s" % sheep_counter
        sys.stdout.flush()
        sheep_counter += 1
        # If signaled to stop then - stop the loop
        if signaled_to_stop:

            print "Stop requested..."
            if signaled_to_stop:
                break

    except KeyboardInterrupt:
        print "\nStopping (might take some seconds).."
        signaled_to_stop = True

    except SystemExit as err:
        raise err

print "Process has finished."