Remove particular permission using os.chmod

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 13:35:45

问题


How can we remove a particular permission for all using os.chmod ?

In short, how can we write the below using os.chmod

chmod a-x filename

I do know that we can add permission to an existing one and remove also.

In [1]: import os, stat
In [5]: os.chmod(file, os.stat(file).st_mode | stat.S_IRGRP)  # Make file group readable.

But I am not able to figure out the doing the all operation


回答1:


Cool. So the secret is you first need to get the current permissions. This is a bit of a mess, but it works.

current = stat.S_IMODE(os.lstat("x").st_mode)

The idea is that lstat.st_mode gives you the flags, but you need to crop that to the range that chmod accepts:

help(stat.S_IMODE)
#>>> Help on built-in function S_IMODE in module _stat:
#>>>
#>>> S_IMODE(...)
#>>>     Return the portion of the file's mode that can be set by os.chmod().
#>>>

Then you can remove the stat.S_IEXEC flag with some bit operations, and this gives you the new number to use:

os.chmod("x", current & ~stat.S_IEXEC)

If you're not familiar with bit twiddling, & takes only those bits that both numbers have, and ~ inverts the bits of a number. so x & ~y takes those bits that x has and that y doesn't have.




回答2:


If you want to use os.chmod() then you can use below code:

import os
for dir_path, dir_names, files in os.walk('.'):
        for file in files:
            abs_path = os.path.join(dirpath, file)
            os.chmod(abs_path, 0o755) 


来源:https://stackoverflow.com/questions/25988471/remove-particular-permission-using-os-chmod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!