Python module os.chmod(file, 664) does not change the permission to rw-rw-r— but -w--wx----

前端 未结 6 973
轮回少年
轮回少年 2020-12-13 01:42

Recently I am using Python module os, when I tried to change the permission of a file, I did not get the expected result. For example, I intended to change the permission to

6条回答
  •  天涯浪人
    2020-12-13 02:27

    Use permission symbols instead of numbers

    Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664:

    #!/usr/bin/env python3
    
    import os
    import stat
    
    os.chmod(
        'myfile',
        stat.S_IRUSR |
        stat.S_IWUSR |
        stat.S_IRGRP |
        stat.S_IWGRP |
        stat.S_IROTH
    )
    

    This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat.

    Another advantage is the greater portability as mentioned in the docs:

    Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

    chmod +x is demonstrated at: How do you do a simple "chmod +x" from within python?

    Tested in Ubuntu 16.04, Python 3.5.2.

提交回复
热议问题