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
If you want to use os.chmod() then you can use below code:
Cool. So the secret is you first need to get the current permissions. This is a bit of a mess, but it works.
The idea is that
lstat.st_mode
gives you the flags, but you need to crop that to the range thatchmod
accepts:Then you can remove the
stat.S_IEXEC
flag with some bit operations, and this gives you the new number to use:If you're not familiar with bit twiddling,
&
takes only those bits that both numbers have, and~
inverts the bits of a number. sox & ~y
takes those bits thatx
has and thaty
doesn't have.