我有下面的类来创建、写入和关闭锁文件。你知道吗
class LockFileManager:
def __init__(self,fname):
"""
Create FileLock and Prepender objects.
"""
self.fname = fname
self.file_lock = FileLock(fname)
self.file_lock.acquire()
self.file_writer = Prepender(fname)
print "LockFile: File lock and writer acquired!\n"
@staticmethod
def add_command(command):
"""
Prepend a command to the LockFile
"""
print "LockFile: Adding command: " + command + "\n"
self.file_writer.write(command)
def end(self):
"""
Close and remove the LockFile
"""
print "LockFile: Closing & Removing LockFile:\n"
self.file_writer.close()
self.file_lock.release()
os.remove(self.fname)
在我的代码主体中,我会这样初始化类:
lockfile = LockFileManager("lockfile.txt")
然后在我的代码中的其他地方,我想写入文件:
LockFileManager.add_command("Write to LockFile provided at initialisation from some arbitrary point in the code ")
然后在代码主体的末尾,调用lockfile.exit()
当我尝试添加命令时,得到NameError occurred: global name 'self' is not defined
。如果self.file_writer.write(command)
更改为file_writer.write(command)
,则它不知道file_writer
是什么。你知道吗
有人知道该怎么做吗?干杯!你知道吗
根据你说的,我相信你在找这样的东西:
然后,只需在需要写入的类中导入
log_file
。你知道吗刚意识到一个模块可能是我最好的选择,我就把这个类改成下面的模块,并达到了我想要的结果
相关问题 更多 >
编程相关推荐