Is there a way to prevent two Python programs from simultaneously running the same binary?

I have two Python scripts that require regular intervals (think cronjobs) to call an external program.

If this program (by which we do not control) is called twice at the same time, data errors occur, so we need to be able to synchronize calls with this binary code.

Is there a way to do this, preferably using only the standard Python library?

+8
python race-condition
source share
1 answer

Thus, without using a third-party library such as filelock , you need to do something like this:

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") 

Better to use filelock (if you can install third-party libraries):

 from filelock import FileLock with FileLock("/path/to/binary"): check_call("/path/to/binary") 

You can easily install filelock with pip :

 $ pip install filelock 

See also similar: Python file lock

Note. . It also seems to be a very similar package called lockfile ! (Do not confuse them!)

+5
source share

All Articles