How do you do a simple “chmod +x” from within python?

前端 未结 7 2316
我寻月下人不归
我寻月下人不归 2020-11-29 19:58

I want to create a file from within a python script that is executable.

import os
import stat
os.chmod(\'somefile\', stat.S_IEXEC)

it appea

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 20:03

    Respect umask like chmod +x

    man chmod says that if augo is not given as in:

    chmod +x mypath
    

    then a is used but with umask:

    A combination of the letters ugoa controls which users' access to the file will be changed: the user who owns it (u), other users in the file's group (g), other users not in the file's group (o), or all users (a). If none of these are given, the effect is as if (a) were given, but bits that are set in the umask are not affected.

    Here is a version that simulates that behavior exactly:

    #!/usr/bin/env python3
    
    import os
    import stat
    
    def get_umask():
        umask = os.umask(0)
        os.umask(umask)
        return umask
    
    def chmod_plus_x(path):
        os.chmod(
            path,
            os.stat(path).st_mode |
            (
                (
                    stat.S_IXUSR |
                    stat.S_IXGRP |
                    stat.S_IXOTH
                )
                & ~get_umask()
            )
        )
    
    chmod_plus_x('.gitignore')
    

    See also: How can I get the default file permissions in Python?

    Tested in Ubuntu 16.04, Python 3.5.2.

提交回复
热议问题