I have the following class for creating, writing to and closing a LockFile.
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)
In my main body of code, I would initialise the class like so:
lockfile = LockFileManager("lockfile.txt")
Then elsewhere in my code, I would like to write to the file:
LockFileManager.add_command("Write to LockFile provided at initialisation from some arbitrary point in the code ")
Then at the end of the main body of code, call lockfile.exit()
When I try to add a command, I get NameError occurred: global name 'self' is not defined
. If self.file_writer.write(command)
is changed to file_writer.write(command)
then it does not know what file_writer
is.
Does anybody know the proper way to go about this? Cheers!