Using the Python stat function to efficiently obtain owner, group, and other permissions

Question:

How to effectively use the stat function to obtain meaningful access rights to files (User, Group and Other).

Details:

I am asking for permissions for files like this:

statInfo = os.stat permissions = stat.S_IMODE ( os.stat ( 'fooBar.txt' ).st_mode ) 

Returns permissions in decimal form. Therefore, if fooBar.txt has permissions for the octal file 0700 , here the permissions are set to decimal 448 . I want to set 9 variables for each permission ( ownerRead , ownerWright , ownerExecute , groupRead , ...) If I were going to do this, I would use brute force

 statInfo = os.stat permissions = stat.S_IMODE ( os.stat ( 'fooBar.txt' ).st_mode ) octPermissions = oct ( permissions ) ownerRead = octPermissions [1] >= 4 ownerWrite = octPermissions [1] == 2 or octPermissions [1] == 6 or octPermissions [1] == 3 or ownerExecute = octPermissions [1] == 1 or octPermissions [1] == 5 or octPermissions [1] == 3 

Is there a more efficient way to do this without having to convert to octal, since this function will be called quite a bit?

+6
source share
3 answers

You can use the bitwise AND operator:

 m = os.stat('fooBar.txt').st_mode otherExec = bool(m & 0001) otherWrite = bool(m & 0002) otherRead = bool(m & 0004) groupExec = bool(m & 0010) groupWrite = bool(m & 0020) groupRead = bool(m & 0040) ... 
+5
source

Use bitwise ANDs and constants in the stat module:

 import stat import os mode = os.stat('fooBar.txt').st_mode otherRead = bool(mode & stat.S_IROTH) otherWrite = bool(mode & stat.S_IWOTH) otherExec = bool(mode & stat.S_IXOTH) ... 

So much more readable.

+5
source

I put this together in a function that gets UNIX permissions:

 import os from stat import (S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH) def bit2int(bit): return int(oct(bit)) def convert_st_mode(st_mode): bits = (S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH) mode = "%03d" % sum(int(bool(st_mode & bit)) * bit2int(bit) for bit in bits) return mode def get_unix_permissions(pth): mode = convert_st_mode(os.stat(pth).st_mode) return mode 

Using:

 mode = get_unix_permissions("somefile") print(mode) 
+3
source

Source: https://habr.com/ru/post/916585/


All Articles