0

I'm trying to get my code to change the group executability permission using os.chmod while keeping all the other permissions in their original state, but I can't seem to figure out how.

All the chmod numbers change all the permissions. I want my program to change the group executability permission to True if it's currently False, and to False if it's currently True

Glyniel
  • 15
  • 4

2 Answers2

3

In order to "flip" the group execute bit you could do this:

import os

os.chmod(filename, os.stat(filename).st_mode ^ 0o10)
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • thanks, that works. However, I don't quite understand the ^ 0o10 part. Would you be able to explain how that flips the group execute? – Glyniel Aug 25 '22 at 13:15
  • @Glyniel The caret is an XOR (bitwise exclusive or). 0o10 is the octal representation of decimal 8 and thus the group execute bit. The effect of XOR is to set a bit on if it's off and vice versa. So, for example, if the file permissions are 0o777 (rwxrwxrwx) and we XOR with 0o10 it becomes 0o767 (rwxrw-rwx). If we then XOR that again with 0o10 it becomes 0o777 (rwxrwxrwx) again – DarkKnight Aug 25 '22 at 16:29
0
stat.S_IMODE(os.stat(your_file).st_mode)

"Return the portion of the file’s mode that can be set by os.chmod() —that is, the file’s permission bits, plus the sticky bit, set-group-id, and set-user-id bits (on systems that support them)."

You can then check what the current permissions are, and modify them as needed.

gimix
  • 3,431
  • 2
  • 5
  • 21
  • OP's challenge is to "flip" the group execute bit i.e., turn on if currently off and vice versa. This code also raises AttributeError on my platform – DarkKnight Aug 17 '22 at 13:58
  • Oops, editing. `S_IMODE` is a function in the `stat` module. I don't know where that `os.` came from – gimix Aug 17 '22 at 14:12
  • Fixed that, I understand OP wants to flip a bit. But I thought a more general answer could be useful, to OP or to someone else in the future – gimix Aug 17 '22 at 14:14