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 ?
Asked
Active
Viewed 250 times
1
-
1Does 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 Answers
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
-
-
Because the lib os is already imported. But it doesn t matter (not an expert in exiting script). I don t know the difference. – Vincent Bénet Dec 13 '21 at 13:13
-
1Read this: https://stackoverflow.com/questions/9591350/what-is-difference-between-sys-exit0-and-os-exit0 – TheEagle Dec 13 '21 at 17:06
-
worked for me, but i dont want creare file like .lock because when remove that work again, I do not want the user to have control over it – Mostafa Dec 17 '21 at 12:14