1

If I execute my long-running Python script multiple times in a row, multiple instances of that script will be running in parallel. But I want that as long as the first instance runs, the others should exit immediately without doing anything. When the first instance exited, the next instance should run again, and so on. How can I do that ?

TheEagle
  • 5,808
  • 3
  • 11
  • 39
Mostafa
  • 11
  • 1
  • 1
    Does this answer your question? [Run python script only if it's not running](https://stackoverflow.com/questions/37968080/run-python-script-only-if-its-not-running) – Chris Dec 13 '21 at 12:35
  • This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why are you trying to do this? – Peter Wood Dec 13 '21 at 12:58
  • Please provide enough code so others can better understand or reproduce the problem. – Community Dec 20 '21 at 20:40

1 Answers1

1

You can create a lock file like this:

import os
import sys
import time

if __name__ == "__main__":
    path_dir = os.path.dirname(__file__)
    path_lock_file = os.path.join(path_dir, ".lock")
    if os.path.isfile(path_lock_file):
        sys.exit(0)
    with open(path_lock_file, "w") as f:
        pass
        
    # You python code down
    time.sleep(10)  # Simulation of you script duration
    # You python code up

    os.remove(path_lock_file)

(Tested) This is NOT the best practice but it is cross Platform.

TheEagle
  • 5,808
  • 3
  • 11
  • 39
Vincent Bénet
  • 1,212
  • 6
  • 20