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.
您需要在系统上发生文件更新之前关闭该文件。你不能阅读或怀疑打开文件。
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)
您只需用日志语句替换所有打印语句即可。
解决方案是使用sys.stdout.flush()。它“动态”更新日志文件。
我可以使用“>”重定向输出
python test.py > result.log
test.朋友
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."