Python:用于创建基于 PID 的锁定文件的模块?
我正在编写一个Python脚本,它可能会也可能不会(取决于很多事情)运行很长时间,并且我想确保多个实例(通过cron启动)不会互相干扰。执行此操作的逻辑方法似乎是基于 PID 的锁定文件……但如果已经有代码可以执行此操作,我不想重新发明轮子。
那么,是否有一个 Python 模块可以管理基于 PID 的锁定文件的详细信息?
I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile… But I don't want to re-invent the wheel if there is already code to do this.
So, is there a Python module out there which will manage the details of a PID-based lockfile?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这可能对您有帮助: lockfile
This might be of help to you: lockfile
如果您可以使用 GPLv2,Mercurial 有一个模块:
http:// bitbucket.org/mirror/mercurial/src/tip/mercurial/lock.py
示例用法:
If you can use GPLv2, Mercurial has a module for that:
http://bitbucket.org/mirror/mercurial/src/tip/mercurial/lock.py
Example usage:
我对所有这些都非常不满意,所以我写了这个:
要使用这样的东西:
i've been pretty unhappy with all of those, so i wrote this:
to be used something like this:
我知道这是一个旧线程,但我还创建了一个简单的锁,它仅依赖于 python 本机库:
I know this is an old thread, but I also created a simple lock which only relies on python native libraries:
我相信您会在此处找到必要的信息。有问题的页面引用了一个用于在 python 中构建守护进程的包:此过程涉及创建 PID 锁定文件。
I believe you will find the necessary information here. The page in question refers to a package for building daemons in python: this process involves creating a PID lockfile.
有一个ActiveState 创建锁定文件的方法。
要生成文件名,您可以使用 os.getpid() 来获取PID。
There is a recipe on ActiveState on creating lockfiles.
To generate the filename you can use os.getpid() to get the PID.
您可以尝试PID:https://pypi.org/project/pid/< /a>
正如文档所示,您只需在函数/方法名称顶部添加装饰器
@pidfile()
即可锁定函数。pidfile 自检的默认位置(指示是否可以执行代码的文件)是“/var/run”。您可以按如下方式更改它:
对于其他参数,请参阅: https ://github.com/trbs/pid/blob/95499b30e8ec4a473c0e6b407c03ce644f61c643/pid/base.py#L41
不幸的是,这个库的文档有点差。
You can try PID: https://pypi.org/project/pid/
As the documentation shows, you can lock a function simply adding the decorator
@pidfile()
on the top of function/method name.The default location for pidfile self check (the file who says if you can execute the code or not) is '/var/run'. You can change it as follows:
For other params, see: https://github.com/trbs/pid/blob/95499b30e8ec4a473c0e6b407c03ce644f61c643/pid/base.py#L41
Unfortunatly, this lib's documentation is a little bit poor.