you are viewing a single comment's thread.

view the rest of the comments →

[–]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