How do you do a simple "chmod +x" from within python?
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)
If you know the permissions you want then the following example may be the way to keep it simple.
Python 2:
os.chmod("/somedir/somefile", 0775)
Python 3:
os.chmod("/somedir/somefile", 0o775)
Compatible with either (octal conversion):
os.chmod("/somedir/somefile", 509)
reference permissions examples