Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple way for Python cron tasks to exit if another process is currently running. Does not use a pidfile.
import os
import subprocess
import shlex
def bail_if_another_is_running():
cmd = shlex.split("pgrep -u {} -f {}".format(os.getuid(), __file__))
pids = subprocess.check_output(cmd).strip().split('\n')
if len(pids) > 1:
pids.remove("{}".format(os.getpid()))
print "Exiting! Found {} is already running (pids): {}".format(
__file__, " ".join(pids))
raise SystemExit(1)
@abhinaythurlapati

This comment has been minimized.

Copy link

abhinaythurlapati commented Aug 20, 2017

Simple and elegant approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.