如果您想创建自己的日志模块,那么您可能需要将已经拥有的内容转换为一个类,以便可以将其作为模块导入。#LoggerThingie.py
import os
import datetime
class LoggerThingie(object):
def __init__(self,fname):
self.fil = open(fname, 'w+')
self.fil.write("# PyIDE Log for" + str(datetime.datetime.now()))
def log(self,strn):
currentTime = datetime.datetime.now()
self.fil.write(str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn)
print str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn
def halt(self):
self.fil.close()
如果你是作为一个类来做的,你就不必一开始就跟踪全局变量(这通常被理解为编程界的坏习惯:Why are global variables evil?)
由于它现在是一个独立的模块,当您想在另一个python程序中使用它时,您可以这样做:from LoggerThingie import LoggerThingie
#because module filename is LoggerThingie.py and ClassName is LoggerThingie
然后在任何需要的地方使用它,例如:x = LoggerThingie('filename.txt') #create LoggerThingie object named x
每次你想插入日志时:x.log('log this to the file')
当你最终完成时:x.halt() # when ur done