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 = ''
fp = open(pid_file, 'w')
    fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
    # another instance is running

Other solutions:
1, Use tendo.
2, Bind a tcp port for locking

Share this post

Post Comment