[英]Python: Creating an empty file object
我试图为Python创建一个无法正常工作的日志记录模块,因为它无法创建文件对象。
debug.py:
import os
import datetime
import globals
global fil
fil = None
def init(fname):
fil = open(fname, 'w+')
fil.write("# PyIDE Log for" + str(datetime.datetime.now()))
def log(strn):
currentTime = datetime.datetime.now()
fil.write(str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn)
print str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn
def halt():
fil.close()
FIL将无法正常工作None
,因为我得到一个AttributeError
。 我也试过创建一个虚拟对象:
fil = open("dummy.tmp","w+")
但是,即使在log()
之前调用init()
,也会写入dummy.tmp
文件。 显然,您无法在已打开的文件上打开新文件。 我试图在init()
之前关闭fil
,但是Python说它无法对已关闭的文件执行write()
。
这是访问debug.py
的代码
if os.path.exists(temp):
os.rename(temp, os.path.join("logs","archived","log-" + str(os.path.getctime(temp)) + ".txt"))
debug.init(globals.logPath)
debug.log("Logger initialized!")
我想登录我的程序,我找不到解决方法。
您的问题是您没有分配给全局fil
:
def init(fname):
fil = open(fname, 'w+')
这将创建一个名为fil
的新局部变量。
如果要分配给全局变量fil
,则需要将其放入本地范围:
def init(fname):
global fil
fil = open(fname, 'w+')
如果您想创建自己的日志记录模块,那么您可能希望将已有的内容转换为类,以便将其作为模块导入。
#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()
如果你把它作为一个类,你就不必首先跟踪全局变量(这通常被理解为编程领域的不良实践: 为什么全局变量是邪恶的? )
既然它现在是一个模块,当你想在另一个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
如果你不想从一个空文件开始,你可以使用StringIO将消息保存在内存中,并在最后将它们写入磁盘,但要小心,如果发生了什么事情并且你没有写入消息,它们就会丢失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.