0

I have python script on Ubuntu, which sometimes running more than 24 hours. I have set in cron, to run this script every day. However if script is still running, I would like to terminate new instance of this script. I have already found some solution, but they seems to be complicated. I would like to add few lines in the beginning of script, which will be checking if the script is running, if yes return, else continue.

I like this command:

pgrep -a python | grep 'script.py'

it is possible to make some smart solution for this problem?

lkip0209
  • 15
  • 1
  • 7

1 Answers1

2

There is no simple way how to do it. As mentioned in comments you can use creation of some locking file. But i prefer use of sockets. Not sure if it works same on Linux but on Windows i use this:

import socket

class AppMutex:
    """
    Class serves as single instance mutex handler (My application can be run only once).
    It use OS default property where single UDP port can be bind only once at time.
    """

    @staticmethod
    def enable():
        """
        By calling this you bind UDP connection on specified port.
        If binding fails then port is already opened from somewhere else.
        """

        try:
            AppMutex.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
            AppMutex.sock.bind(("127.0.0.1", 40000))
        except OSError:
            raise Exception("Application can be run only once.")

Simple call at begining of your script:

AppMutex.enable()
Erik Šťastný
  • 1,487
  • 1
  • 15
  • 41