使用os.chmod删除特定权限 [英] Remove particular permission using os.chmod

查看:173
本文介绍了使用os.chmod删除特定权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用os.chmod删除所有用户的特定权限?

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

简而言之,我们如何使用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

推荐答案

很酷.因此秘诀是您首先需要获得当前权限.这有点混乱,但是可以.

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)

想法是lstat.st_mode为您提供标志,但是您需要将其裁剪到chmod可以接受的范围:

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().
#>>>

然后您可以通过一些位操作删除stat.S_IEXEC标志,这将为您提供新的编号:

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)

如果您不熟悉位旋转,则&仅采用两个数字都具有的那些位,而~会将数字的位取反.因此x & ~y会使用x拥有的和y 没有拥有的那些位.

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.

这篇关于使用os.chmod删除特定权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆