制作了一个锁文件,但是多处理会破坏它

时间:2017-11-09 03:34:24

标签: python locking python-multiprocessing

我为我的脚本创建了一个锁文件函数,这样一次只能运行一个实例。一切都应该可以正常工作,但是如果我使用多处理它会产生错误The process cannot access the file because it is being used by another process,即使它只在主进程中使用。

我一直试图将它修好几个小时而没有运气,我想知道是否有其他人可能会提出修复方案?我几乎包裹了try/except KeyboardInterrupt中的每个部分,运行p.terminate()以强制关闭进程,然后删除文件,使用和不带damon标记,将lock传递给主脚本和功能结束时的早期删除等,我现在完全没有想法。

编辑:我在另一种情况下再次遇到同样的问题(绝对痛苦地解决,最后我不得不弄清楚另一种做事方式),所以仍然很好奇是否有人可以放弃任何光线在这个问题上。

锁定课程:

import os
OSError = FileNotFoundError = WindowsError = IOError

class Lock(object):
    """Stop two versions of the script from being loaded at the same time."""
    def __init__(self, filename):
        self.filename = filename
        self.closed = False

    def __enter__(self):
        #Create file if it doesn't exist (probably need to rewrite with os.exists instead)
        try:
            with open(self.filename, 'w') as f:
                pass
        except IOError:
            pass

        #Check if file is locked, or create a new one
        try:
            os.remove(self.filename)
        except IOError:
            self._file = None
        else:
            self._file = open(self.filename, 'w')
        return self

    def __exit__(self, *args):
        self.close()

    def __bool__(self):
        return self._file is not None
    __nonzero__ = __bool__

    def close(self):
        """Close the locked file."""
        if not self.closed:
            if self._file is not None:
                self._file.close()
            self.closed = True
            os.remove(self.filename)

代码不起作用(如果你注释掉p.start()则开始工作):

from multiprocessing import Process
import time

def main():
    p = Process(target=background)
    p.daemon = True
    p.start()
    while True:
        time.sleep(0.05)
        print time.time()

def background():
    while True:
        pass

if __name__ == '__main__':
    with Lock('C:/Users/Peter/Python/lock.tmp') as lock:
        if lock:
            main()
        else:
            print 'already running'

如果它已关闭或您点击了ctrl + c,则收到此消息,文件仍为:

Traceback (most recent call last):
  File "C:\Users\Peter\Python\test.py", line 77, in <module>
    print 'already running'
  File "C:\Users\Peter\Python\test.py", line 24, in __exit__
    self.close()
  File "C:\Users\Peter\Python\test.py", line 55, in close
    os.remove(self.filename)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'C:/Users/Peter/Python/lock.tmp'

就像我上面提到的那样,我尝试了很多变化,但似乎没有任何效果。 Python不能立即关闭文件,有没有办法强迫它?

0 个答案:

没有答案