On 18Apr2017 19:31, Matt <matt.mailingli...@gmail.com> wrote:
I have a number of simple scripts I run with cron hourly on Centos
linux. I want the script to check first thing if its already running
and if so exit.
In perl I did it with this at the start of every script:
use Fcntl ':flock';
INIT {
open LH, $0 or die "Can't open $0 for locking!\nError: $!\n";
flock LH, LOCK_EX | LOCK_NB or die "$0 is already running somewhere!\n";
}
How can I do something like this in Python?
Others have pointed the way to an exact implementation.
For myself, I like mkdir. It is portable. It is atomic. It fails if the target
exists. It works over NFS etc. It is easy.
os.mkdir('lock')
... do stuff ...
os.rmdir('lock')
and it is equally doable in a shell script (eg your cron job):
if mkdir lockdir
then
... do stuff ...
rmdir lockdir
else
echo "lockdir already takens, aborting" >&2
exit 1
fi
which means you don't need to fit the lock logic inside every tool, you can
just do it in the script that calls them.
Cheers,
Cameron Simpson <c...@zip.com.au>
--
https://mail.python.org/mailman/listinfo/python-list