+ 1
How to prevent secondary access of a file?
I wrote a few scripts that open files and manipulate data (either regular open or pickle). I auto-save with every in-program change I do with the data. Now when I accidentally open another instance of my script, and it accesses the same file, everything gets messed up. So I'd like to know how I can reliably block access of that file for everybody else, while the script is running. If possible, I'd like to do it without keeping the file open the whole time... Any ideas?
7 ответов
+ 5
I assume the other instance as you call it is the same code as the file that is allowed to open and process the file. I also assume all is running in the same computer.
So you have a chance if you can run the scripts from different directories, and check this before accessing your data files. So one instance has permission to open file, the other instance does not have permission.
Here is a link that is describing something like that.
If this is not possible, you might ask user a login (user or admin) so that only if admin is logged in there is access for the file.
+ 5
HonFu, here is bit of code that does check from which directory the file is running
import os
dirname, filename = os.path.split(os.path.abspath(__file__))
print("running from", dirname)
print("\nfile is", filename)
running from /private/var/mobile/Containers/Shared/Pythonista3/Documents
file is file_access.py
running from /private/var/mobile/Containers/Shared/Pythonista3/Documents/Examples
file is file_access.py
+ 3
~ swim ~, thanks, you helped me cook up something that seems to work!
Lothar, that sounds like a good idea in many cases, thanks!
But in this case enforcing that the script doesn't run twice seems to be the best idea - or at least the laziest. 😉
https://code.sololearn.com/crUF0NtYFp1W/?ref=app
+ 1
Ey guys i quite new to this game