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

priestc picture priestc · Oct 9, 2012 · Viewed 92.9k times · Source

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 appears os.chmod doesn't 'add' permissions the way unix chmod does. With the last line commented out, the file has the filemode -rw-r--r--, with it not commented out, the file mode is ---x------. How can I just add the u+x flag while keeping the rest of the modes intact?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 9, 2012

Use os.stat() to get the current permissions, use | to or the bits together, and use os.chmod() to set the updated permissions.

Example:

import os
import stat

st = os.stat('somefile')
os.chmod('somefile', st.st_mode | stat.S_IEXEC)