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

前端 未结 7 2334
我寻月下人不归
我寻月下人不归 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

    For tools that generate executable files (e.g. scripts), the following code might be helpful:

    def make_executable(path):
        mode = os.stat(path).st_mode
        mode |= (mode & 0o444) >> 2    # copy R bits to X
        os.chmod(path, mode)
    

    This makes it (more or less) respect the umask that was in effect when the file was created: Executable is only set for those that can read.

    Usage:

    path = 'foo.sh'
    with open(path, 'w') as f:           # umask in effect when file is created
        f.write('#!/bin/sh\n')
        f.write('echo "hello world"\n')
    
    make_executable(path)
    

提交回复
热议问题