从初始化的elsewh类调用静态方法

2024-06-16 14:17:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的类来创建、写入和关闭锁文件。你知道吗

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是什么。你知道吗

有人知道该怎么做吗?干杯!你知道吗


Tags: andthe代码selflockdeffnamecommand
2条回答

根据你说的,我相信你在找这样的东西:

from threading import Lock

class LockFile(file):
    def __init__(self, *args, **kwargs):
        super(LockFile, self).__init__(*args, **kwargs)
        self._lock = Lock()

    def write(self, *args, **kwargs):
        with self._lock:
            super(LockFile, self).write(*args, **kwargs)

log_file = LockFile('path/to/logfile', 'w')

然后,只需在需要写入的类中导入log_file。你知道吗

刚意识到一个模块可能是我最好的选择,我就把这个类改成下面的模块,并达到了我想要的结果

def start(fname):
    """
    Create FileLock and Prepender objects.
    """
    global lockfile_name
    global file_lock
    global file_writer

    lockfile_name = fname

    file_lock = FileLock(fname)
    file_lock.acquire()

    file_writer = Prepender(fname)

    print "LockFile: File lock and writer acquired!\n"


def add_command(command):
    """
    Prepend a command to the LockFile
    """
    print "LockFile: Adding command: " + command + "\n"
    file_writer.write(command)

def end():
    """
    Close and remove the LockFile
    """
    print "LockFile: Closing & Removing LockFile:\n"
    file_writer.close()
    file_lock.release()

    os.remove(self.fname)

相关问题 更多 >