Python: block directory access under windows

I would like to be able to block access to the directory under the windows. The following code works very hard with a file or directory on a POSIX system:

def flock(fd, blocking=False, exclusive=False): if exclusive: flags = fcntl.LOCK_EX else: flags = fcntl.LOCK_SH if not blocking: flags |= fcntl.LOCK_NB fcntl.flock(fd, flags) 

But I only find a way to do access blocking for a file, not a directory with the following code:

 def flock(fd, blocking=False, exclusive=False): if blocking: flags = msvcrt.LK_NBLCK else: flags = msvcrt.LK_LOCK msvcrt.locking(fd.fileno(), flags, os.path.getsize(fd.name)) 

Do you have an idea how to improve this code and block access to the directory?

Bertrand

+4
source share
3 answers

I do not consider it possible to use flock () in directories in windows. PHP docs on flock () indicate that it will not even work with FAT32 file systems.

On the other hand, Windows no longer allows you to delete files / directories if any files are still open. This, plus, perhaps using an ACL wisely, can help you get a 95% equivalent solution.

+1
source

You can probably do something similar to indirectly lock the directory using the latest flock function.

 for file in os.listdir(dir): f = open(file) flock(f) 

This is a limited version, as the user will be able to create new files in the directory.

0
source

Yes, you're right, at least I can try to lock every directory file, but it can be painful because I need to go to all the subdirectories of my directory. On a POSIX system, this is easy because directories are treated as files, so there is no problem with that. But on Windows, when I try to open a directory, I don’t really like it.

 open(dirname) 

throws an exception:

 OSError: [Errno 13] Permission denied: dirname 

I'm not sure if my decision is actually a good way to do this.

0
source

All Articles