Running a script with sudo means that you are running it as root. So usually your file is owned by root.
What you can do is change the ownership of the file after it is created. To do this, you need to know which user is running sudo. Fortunately, there is an SUDO_UID environment variable that is set when using sudo.
So you can do:
import os print(os.environ.get('SUDO_UID'))
Then you need to change the owner of the file :
os.chown("path/to/file", uid, gid)
If you put this together:
import os uid = int(os.environ.get('SUDO_UID')) gid = int(os.environ.get('SUDO_GID')) os.chown("path/to/file", uid, gid)
Of course, you will want it as a function, because it is more convenient, therefore:
import os def fix_ownership(path): """Change the owner of the file to SUDO_UID""" uid = os.environ.get('SUDO_UID') gid = os.environ.get('SUDO_GID') if uid is not None: os.chown(path, int(uid), int(gid)) def get_file(path, mode="a+"): """Create a file if it does not exists, fix ownership and return it open"""
Using:
EDIT: Updated my answer thanks to @Basilevs, @ Robα΅© and @ 5gon12eder
Eliot berriot
source share