How to avoid multiple instances of a Python script?

How can I prevent running multiple instances of a python program, as I have to ensure a single instance of an program in Linux?
We already have a solution for Shell and Perl scripts, but didn’t offer a solution for Python scripts.

It basically follows the same way, here it is,

import fcntl, sys
pid_file = 'program.pid'
fp = open(pid_file, 'w')
try:
    fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
    # another instance is running
    sys.exit(0)

Other solutions:
1, Use tendo.
http://pythonhosted.org/tendo/
2, Bind a tcp port for locking

Share Button

Leave a comment

Your email address will not be published. Required fields are marked *