nb-filelock


Namenb-filelock JSON
Version 0.9 PyPI version JSON
download
home_pageNone
Summaryfilelock ,it can run on linux and windows
upload_time2024-05-27 02:34:10
maintainerydf
docs_urlNone
authorbfzs
requires_pythonNone
licenseBSD License
keywords filelock multiprocessing lock
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ## 1. pip install nb_filelock

基于代码所在机器的跨进程 跨解释器的文件互斥锁。兼容windwos和linux

filelock,which can run on linux and windwos.

## 文件锁的功能意义
```
此文件锁并不是为了解决多个python程序写入同一个txt文件的问题(当然顺便也解决了这个问题),
而是借助文件锁这种中间件介质(类比redis分布式锁使用redis做中间件介质),
从而实现当前机器无论启动多少次脚本,只有一个脚本能获得锁从而执行锁里面的代码块。
```

## 各种锁的能力影响范围大小

锁的能力范围大小是  多线程锁  <  多进程锁  <  文件锁  <  redis分布式锁。

```
线程锁只能确保单一进程的不同线程只有一个线程能获得锁从而执行代码块

多进程锁针对不同进程,但有个前提是,进程必须是这么饿启动的,
例如 a.py 文件,在a.py文件里面的代码需要引用muliprossing包的Process(target=func).start()来启动多进程
如果是把 a.py反复手动运行两次,而不是用了muliprossing包来一次性启动的,两次a.py的进程完全毫不相关,
这种不同的脚本进程彼此没法知道另一个进程里面的变量,此时需要引入一种中间介质,每个脚本都去读取这个中间件介质来获得锁才可以,
可以使用redis分布式锁,但这种比较烦需要安装一个redis,没安装redis的环境代码就无法运行了。所以就是要开发一种文件锁,不需要安装中间件。

文件锁, 影响范围是当前机器,能够跨不同批次的启动脚本的解释器,确保代码里面只有一个地方能获得文件锁,从而执行代码块。
比如希望在当前机器只能同时运行某一个代码块,完全豪不相关的两次启动xx.py,没有办法使用进程锁,
压根就不是使用multiprossing包同时启动的多个子进程而是手动两次运行了python xx.py,
好的方式是使用redis分布式锁,可以保证所有机器只提示一个获得锁,但如果没安装redis切要保证当前机器只有一个能执行代码块,就需要这个。


redis分布式锁,能影响的范围最强力最广泛,不进能够跨本机的解释器,还能跨机器,可以确保几百台电脑只有一个地方能获得锁从而执行代码块,但要安装redis。
```


### 测试例子。

```
把下面的python文件复制到一个文件中叫test.py,然后重复启动两次 python test.py,
当第一个脚本还没执行完代码块时候,另一个脚本会等待第一个脚本执行完成代码块的语句才会开始print hi。
```

```python
import nb_log
import time
from nb_filelock import FileLock

print('wait filelock')
with FileLock('testx.lock'):
    print('hi')
    time.sleep(20)
    print('hello')
```

### 实现代码
```python
import os
import abc

if os.name == 'nt':
    import win32con, win32file, pywintypes

    LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
    LOCK_SH = 0  # The default value
    LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
    _overlapped = pywintypes.OVERLAPPED()  # noqa
else:
    import fcntl


class BaseLock(metaclass=abc.ABCMeta):
    def __init__(self, lock_file_path: str):
        self.f = open(lock_file_path, 'a')

    @abc.abstractmethod
    def __enter__(self):
        raise NotImplemented

    @abc.abstractmethod
    def __exit__(self, exc_type, exc_val, exc_tb):
        raise NotImplemented


class WindwosFileLock(BaseLock):
    def __enter__(self):
        hfile = win32file._get_osfhandle(self.f.fileno())
        win32file.LockFileEx(hfile, LOCK_EX, 0, 0xffff0000, _overlapped)

    def __exit__(self, exc_type, exc_val, exc_tb):
        hfile = win32file._get_osfhandle(self.f.fileno())
        win32file.UnlockFileEx(hfile, 0, 0xffff0000, _overlapped)


class LinuxFileLock(BaseLock):
    def __enter__(self):
        fcntl.flock(self.f, fcntl.LOCK_EX)

    def __exit__(self, exc_type, exc_val, exc_tb):
        fcntl.flock(self.f, fcntl.LOCK_UN)


FileLock = WindwosFileLock if os.name == 'nt' else LinuxFileLock

if __name__ == '__main__':
    """ 把这个脚本连续反复启动多个可以测试文件锁,只有获得文件锁,代码块才能执行"""
    import nb_log
    import time

    print('等待获得锁')
    with FileLock('testx.lock'):
        print('hi')
        time.sleep(20)
        print('hello')
    

```




多个脚本都并发写入一个txt文件可以这样。
```
with FileLock('D:/testyy.lock'):
    with open("yourtxt.txt","a") as f:
           f.write("xxxx")
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "nb-filelock",
    "maintainer": "ydf",
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": "ydf0509@sohu.com",
    "keywords": "filelock, multiprocessing lock",
    "author": "bfzs",
    "author_email": "ydf0509@sohu.com",
    "download_url": "https://files.pythonhosted.org/packages/4a/2b/9cf11c8dc87a69361caa5f11297f23d661ab89873cfcd6c175b9b3ada295/nb_filelock-0.9.tar.gz",
    "platform": "all",
    "description": "## 1. pip install nb_filelock\r\n\r\n\u57fa\u4e8e\u4ee3\u7801\u6240\u5728\u673a\u5668\u7684\u8de8\u8fdb\u7a0b \u8de8\u89e3\u91ca\u5668\u7684\u6587\u4ef6\u4e92\u65a5\u9501\u3002\u517c\u5bb9windwos\u548clinux\r\n\r\nfilelock,which can run on linux and windwos.\r\n\r\n## \u6587\u4ef6\u9501\u7684\u529f\u80fd\u610f\u4e49\r\n```\r\n\u6b64\u6587\u4ef6\u9501\u5e76\u4e0d\u662f\u4e3a\u4e86\u89e3\u51b3\u591a\u4e2apython\u7a0b\u5e8f\u5199\u5165\u540c\u4e00\u4e2atxt\u6587\u4ef6\u7684\u95ee\u9898(\u5f53\u7136\u987a\u4fbf\u4e5f\u89e3\u51b3\u4e86\u8fd9\u4e2a\u95ee\u9898)\uff0c\r\n\u800c\u662f\u501f\u52a9\u6587\u4ef6\u9501\u8fd9\u79cd\u4e2d\u95f4\u4ef6\u4ecb\u8d28(\u7c7b\u6bd4redis\u5206\u5e03\u5f0f\u9501\u4f7f\u7528redis\u505a\u4e2d\u95f4\u4ef6\u4ecb\u8d28)\uff0c\r\n\u4ece\u800c\u5b9e\u73b0\u5f53\u524d\u673a\u5668\u65e0\u8bba\u542f\u52a8\u591a\u5c11\u6b21\u811a\u672c\uff0c\u53ea\u6709\u4e00\u4e2a\u811a\u672c\u80fd\u83b7\u5f97\u9501\u4ece\u800c\u6267\u884c\u9501\u91cc\u9762\u7684\u4ee3\u7801\u5757\u3002\r\n```\r\n\r\n## \u5404\u79cd\u9501\u7684\u80fd\u529b\u5f71\u54cd\u8303\u56f4\u5927\u5c0f\r\n\r\n\u9501\u7684\u80fd\u529b\u8303\u56f4\u5927\u5c0f\u662f  \u591a\u7ebf\u7a0b\u9501  <  \u591a\u8fdb\u7a0b\u9501  <  \u6587\u4ef6\u9501  <  redis\u5206\u5e03\u5f0f\u9501\u3002\r\n\r\n```\r\n\u7ebf\u7a0b\u9501\u53ea\u80fd\u786e\u4fdd\u5355\u4e00\u8fdb\u7a0b\u7684\u4e0d\u540c\u7ebf\u7a0b\u53ea\u6709\u4e00\u4e2a\u7ebf\u7a0b\u80fd\u83b7\u5f97\u9501\u4ece\u800c\u6267\u884c\u4ee3\u7801\u5757\r\n\r\n\u591a\u8fdb\u7a0b\u9501\u9488\u5bf9\u4e0d\u540c\u8fdb\u7a0b\uff0c\u4f46\u6709\u4e2a\u524d\u63d0\u662f\uff0c\u8fdb\u7a0b\u5fc5\u987b\u662f\u8fd9\u4e48\u997f\u542f\u52a8\u7684\uff0c\r\n\u4f8b\u5982 a.py \u6587\u4ef6\uff0c\u5728a.py\u6587\u4ef6\u91cc\u9762\u7684\u4ee3\u7801\u9700\u8981\u5f15\u7528muliprossing\u5305\u7684Process(target=func).start()\u6765\u542f\u52a8\u591a\u8fdb\u7a0b\r\n\u5982\u679c\u662f\u628a a.py\u53cd\u590d\u624b\u52a8\u8fd0\u884c\u4e24\u6b21\uff0c\u800c\u4e0d\u662f\u7528\u4e86muliprossing\u5305\u6765\u4e00\u6b21\u6027\u542f\u52a8\u7684\uff0c\u4e24\u6b21a.py\u7684\u8fdb\u7a0b\u5b8c\u5168\u6beb\u4e0d\u76f8\u5173\uff0c\r\n\u8fd9\u79cd\u4e0d\u540c\u7684\u811a\u672c\u8fdb\u7a0b\u5f7c\u6b64\u6ca1\u6cd5\u77e5\u9053\u53e6\u4e00\u4e2a\u8fdb\u7a0b\u91cc\u9762\u7684\u53d8\u91cf\uff0c\u6b64\u65f6\u9700\u8981\u5f15\u5165\u4e00\u79cd\u4e2d\u95f4\u4ecb\u8d28\uff0c\u6bcf\u4e2a\u811a\u672c\u90fd\u53bb\u8bfb\u53d6\u8fd9\u4e2a\u4e2d\u95f4\u4ef6\u4ecb\u8d28\u6765\u83b7\u5f97\u9501\u624d\u53ef\u4ee5\uff0c\r\n\u53ef\u4ee5\u4f7f\u7528redis\u5206\u5e03\u5f0f\u9501\uff0c\u4f46\u8fd9\u79cd\u6bd4\u8f83\u70e6\u9700\u8981\u5b89\u88c5\u4e00\u4e2aredis\uff0c\u6ca1\u5b89\u88c5redis\u7684\u73af\u5883\u4ee3\u7801\u5c31\u65e0\u6cd5\u8fd0\u884c\u4e86\u3002\u6240\u4ee5\u5c31\u662f\u8981\u5f00\u53d1\u4e00\u79cd\u6587\u4ef6\u9501\uff0c\u4e0d\u9700\u8981\u5b89\u88c5\u4e2d\u95f4\u4ef6\u3002\r\n\r\n\u6587\u4ef6\u9501, \u5f71\u54cd\u8303\u56f4\u662f\u5f53\u524d\u673a\u5668\uff0c\u80fd\u591f\u8de8\u4e0d\u540c\u6279\u6b21\u7684\u542f\u52a8\u811a\u672c\u7684\u89e3\u91ca\u5668\uff0c\u786e\u4fdd\u4ee3\u7801\u91cc\u9762\u53ea\u6709\u4e00\u4e2a\u5730\u65b9\u80fd\u83b7\u5f97\u6587\u4ef6\u9501\uff0c\u4ece\u800c\u6267\u884c\u4ee3\u7801\u5757\u3002\r\n\u6bd4\u5982\u5e0c\u671b\u5728\u5f53\u524d\u673a\u5668\u53ea\u80fd\u540c\u65f6\u8fd0\u884c\u67d0\u4e00\u4e2a\u4ee3\u7801\u5757\uff0c\u5b8c\u5168\u8c6a\u4e0d\u76f8\u5173\u7684\u4e24\u6b21\u542f\u52a8xx.py\uff0c\u6ca1\u6709\u529e\u6cd5\u4f7f\u7528\u8fdb\u7a0b\u9501\uff0c\r\n\u538b\u6839\u5c31\u4e0d\u662f\u4f7f\u7528multiprossing\u5305\u540c\u65f6\u542f\u52a8\u7684\u591a\u4e2a\u5b50\u8fdb\u7a0b\u800c\u662f\u624b\u52a8\u4e24\u6b21\u8fd0\u884c\u4e86python xx.py\uff0c\r\n\u597d\u7684\u65b9\u5f0f\u662f\u4f7f\u7528redis\u5206\u5e03\u5f0f\u9501\uff0c\u53ef\u4ee5\u4fdd\u8bc1\u6240\u6709\u673a\u5668\u53ea\u63d0\u793a\u4e00\u4e2a\u83b7\u5f97\u9501\uff0c\u4f46\u5982\u679c\u6ca1\u5b89\u88c5redis\u5207\u8981\u4fdd\u8bc1\u5f53\u524d\u673a\u5668\u53ea\u6709\u4e00\u4e2a\u80fd\u6267\u884c\u4ee3\u7801\u5757\uff0c\u5c31\u9700\u8981\u8fd9\u4e2a\u3002\r\n\r\n\r\nredis\u5206\u5e03\u5f0f\u9501\uff0c\u80fd\u5f71\u54cd\u7684\u8303\u56f4\u6700\u5f3a\u529b\u6700\u5e7f\u6cdb\uff0c\u4e0d\u8fdb\u80fd\u591f\u8de8\u672c\u673a\u7684\u89e3\u91ca\u5668\uff0c\u8fd8\u80fd\u8de8\u673a\u5668\uff0c\u53ef\u4ee5\u786e\u4fdd\u51e0\u767e\u53f0\u7535\u8111\u53ea\u6709\u4e00\u4e2a\u5730\u65b9\u80fd\u83b7\u5f97\u9501\u4ece\u800c\u6267\u884c\u4ee3\u7801\u5757\uff0c\u4f46\u8981\u5b89\u88c5redis\u3002\r\n```\r\n\r\n\r\n### \u6d4b\u8bd5\u4f8b\u5b50\u3002\r\n\r\n```\r\n\u628a\u4e0b\u9762\u7684python\u6587\u4ef6\u590d\u5236\u5230\u4e00\u4e2a\u6587\u4ef6\u4e2d\u53ebtest.py,\u7136\u540e\u91cd\u590d\u542f\u52a8\u4e24\u6b21 python test.py\uff0c\r\n\u5f53\u7b2c\u4e00\u4e2a\u811a\u672c\u8fd8\u6ca1\u6267\u884c\u5b8c\u4ee3\u7801\u5757\u65f6\u5019\uff0c\u53e6\u4e00\u4e2a\u811a\u672c\u4f1a\u7b49\u5f85\u7b2c\u4e00\u4e2a\u811a\u672c\u6267\u884c\u5b8c\u6210\u4ee3\u7801\u5757\u7684\u8bed\u53e5\u624d\u4f1a\u5f00\u59cbprint hi\u3002\r\n```\r\n\r\n```python\r\nimport nb_log\r\nimport time\r\nfrom nb_filelock import FileLock\r\n\r\nprint('wait filelock')\r\nwith FileLock('testx.lock'):\r\n    print('hi')\r\n    time.sleep(20)\r\n    print('hello')\r\n```\r\n\r\n### \u5b9e\u73b0\u4ee3\u7801\r\n```python\r\nimport os\r\nimport abc\r\n\r\nif os.name == 'nt':\r\n    import win32con, win32file, pywintypes\r\n\r\n    LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK\r\n    LOCK_SH = 0  # The default value\r\n    LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY\r\n    _overlapped = pywintypes.OVERLAPPED()  # noqa\r\nelse:\r\n    import fcntl\r\n\r\n\r\nclass BaseLock(metaclass=abc.ABCMeta):\r\n    def __init__(self, lock_file_path: str):\r\n        self.f = open(lock_file_path, 'a')\r\n\r\n    @abc.abstractmethod\r\n    def __enter__(self):\r\n        raise NotImplemented\r\n\r\n    @abc.abstractmethod\r\n    def __exit__(self, exc_type, exc_val, exc_tb):\r\n        raise NotImplemented\r\n\r\n\r\nclass WindwosFileLock(BaseLock):\r\n    def __enter__(self):\r\n        hfile = win32file._get_osfhandle(self.f.fileno())\r\n        win32file.LockFileEx(hfile, LOCK_EX, 0, 0xffff0000, _overlapped)\r\n\r\n    def __exit__(self, exc_type, exc_val, exc_tb):\r\n        hfile = win32file._get_osfhandle(self.f.fileno())\r\n        win32file.UnlockFileEx(hfile, 0, 0xffff0000, _overlapped)\r\n\r\n\r\nclass LinuxFileLock(BaseLock):\r\n    def __enter__(self):\r\n        fcntl.flock(self.f, fcntl.LOCK_EX)\r\n\r\n    def __exit__(self, exc_type, exc_val, exc_tb):\r\n        fcntl.flock(self.f, fcntl.LOCK_UN)\r\n\r\n\r\nFileLock = WindwosFileLock if os.name == 'nt' else LinuxFileLock\r\n\r\nif __name__ == '__main__':\r\n    \"\"\" \u628a\u8fd9\u4e2a\u811a\u672c\u8fde\u7eed\u53cd\u590d\u542f\u52a8\u591a\u4e2a\u53ef\u4ee5\u6d4b\u8bd5\u6587\u4ef6\u9501\uff0c\u53ea\u6709\u83b7\u5f97\u6587\u4ef6\u9501\uff0c\u4ee3\u7801\u5757\u624d\u80fd\u6267\u884c\"\"\"\r\n    import nb_log\r\n    import time\r\n\r\n    print('\u7b49\u5f85\u83b7\u5f97\u9501')\r\n    with FileLock('testx.lock'):\r\n        print('hi')\r\n        time.sleep(20)\r\n        print('hello')\r\n    \r\n\r\n```\r\n\r\n\r\n\r\n\r\n\u591a\u4e2a\u811a\u672c\u90fd\u5e76\u53d1\u5199\u5165\u4e00\u4e2atxt\u6587\u4ef6\u53ef\u4ee5\u8fd9\u6837\u3002\r\n```\r\nwith FileLock('D:/testyy.lock'):\r\n    with open(\"yourtxt.txt\",\"a\") as f:\r\n           f.write(\"xxxx\")\r\n```\r\n",
    "bugtrack_url": null,
    "license": "BSD License",
    "summary": "filelock ,it can run on linux and windows",
    "version": "0.9",
    "project_urls": null,
    "split_keywords": [
        "filelock",
        " multiprocessing lock"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4a2b9cf11c8dc87a69361caa5f11297f23d661ab89873cfcd6c175b9b3ada295",
                "md5": "45f6bcb9b566150d290a5764718349d4",
                "sha256": "3a7def5db52d9e537875c5554100716eb430f9f3e18b0607d5bdb8c7d07e5dfd"
            },
            "downloads": -1,
            "filename": "nb_filelock-0.9.tar.gz",
            "has_sig": false,
            "md5_digest": "45f6bcb9b566150d290a5764718349d4",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 4593,
            "upload_time": "2024-05-27T02:34:10",
            "upload_time_iso_8601": "2024-05-27T02:34:10.490181Z",
            "url": "https://files.pythonhosted.org/packages/4a/2b/9cf11c8dc87a69361caa5f11297f23d661ab89873cfcd6c175b9b3ada295/nb_filelock-0.9.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-27 02:34:10",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "nb-filelock"
}
        
Elapsed time: 0.33523s