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

|

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

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?

👻 Read also: what is the best laptop for engineering students?

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

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

1 answers

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?

145

Answer #1

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)

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method