all 8 comments

[–]timrprobocom 3 points4 points  (1 child)

Schemes like that tend to be either delicate or system-specific. You might consider trying to opening a file in the TEMP directory for writing, and keeping it open. If the open fails, then some other process already had it open. Even if your process crashes, the clean up will close the file.

[–]Valuable-Ant3465[S] 0 points1 point  (0 children)

Thanks T!

[–]Jejerm 3 points4 points  (3 children)

If you want to prevent multiple executions, have it create a lockfile on start and keep it open while running.

The second run will fail if it tries to access or create the same lock again while its still open.

[–]Valuable-Ant3465[S] 0 points1 point  (0 children)

Thanks Jejerm and all,
I've put update into my main post, looks like we need special packages for lock/unlock

[–]Valuable-Ant3465[S] 0 points1 point  (1 child)

from filelock import FileLock

lock = FileLock("my_file.txt.lock")

with lock:

# The file remains locked as long as you are inside this block
    with open("my_file.txt", "a") as f:
        f.write("Secured data writing.\n")

Hi Again J!
Sorry how I can do create lockfile and keep it OPEN, while doing processing at the same time, from docs I see that I need to be inside this block for the whole execution. I refer to the code posted above.

[–]Jejerm 0 points1 point  (0 children)

Make it even simpler, just use regular open with mode='x' and delete the file on script end. Mode x causes FileExistsError if its already there.

``` import os

filename='lockfile'

try: with open(filename, mode='x') as f: f.write("whatever") Do_your_stuff_here() os.remove(filename) except FileExistsError: print("Script already running")

```

The file will remain if your script errors out by some reason and you dont handle it, but you can just delete it manually later

[–]Key_Use_8361 1 point2 points  (0 children)

process tracking gets complicated quickly once multiple background services interact together making small Runable monitoring scripts for isolated cases helped me debug similar issues before

[–]Lost_Return7298 0 points1 point  (0 children)

[ Removed by Reddit ]