有没有办法防止两个 Python 程序同时执行同一个二进制文件?
Is there a way to prevent two Python programs from executing the same binary at the same time?
我有两个 Python 脚本,它们都需要定期(想想 cronjobs)来调用外部程序。
如果这个程序(我们无法控制)被同时调用两次,就会发生数据错误,所以我们需要有一种方法来同步对这个二进制文件的调用。
有没有办法做到这一点,最好只使用 Python 标准库?
因此,如果不使用 filelock 等第 3 方库,您必须执行以下操作:
import os
from subprocess import check_call
if os.path.exists("/var/run/foo.ock"):
print("Backing off...")
raise SystemExit(1)
try:
with open("/var/run/foo.lock", "w"):
check_call("/path/to/binary")
finally:
os.remove("/var/run/foo.lock")
更好的方法是使用filelock(如果你可以安装第 3 方库):
from filelock import FileLock
with FileLock("/path/to/binary"):
check_call("/path/to/binary")
$ pip install filelock
另见相关:Locking a file in Python
注:似乎还有一个非常相似的包名为lockfile! (不要混淆两者!)
我有两个 Python 脚本,它们都需要定期(想想 cronjobs)来调用外部程序。
如果这个程序(我们无法控制)被同时调用两次,就会发生数据错误,所以我们需要有一种方法来同步对这个二进制文件的调用。
有没有办法做到这一点,最好只使用 Python 标准库?
因此,如果不使用 filelock 等第 3 方库,您必须执行以下操作:
import os
from subprocess import check_call
if os.path.exists("/var/run/foo.ock"):
print("Backing off...")
raise SystemExit(1)
try:
with open("/var/run/foo.lock", "w"):
check_call("/path/to/binary")
finally:
os.remove("/var/run/foo.lock")
更好的方法是使用filelock(如果你可以安装第 3 方库):
from filelock import FileLock
with FileLock("/path/to/binary"):
check_call("/path/to/binary")
$ pip install filelock
另见相关:Locking a file in Python
注:似乎还有一个非常相似的包名为lockfile! (不要混淆两者!)