Laufen Ihr Skript mit sudo bedeutet, dass Sie es als root ausführen. Es ist also normal, dass Ihre Datei im Besitz von root ist.
Sie können die Eigentümerschaft der Datei ändern, nachdem sie erstellt wurde. Um dies zu tun, müssen Sie wissen, welcher Benutzer sudo ausführt. Glücklicherweise gibt es eine SUDO_UID
Umgebungsvariable, die gesetzt wird, wenn Sie sudo verwenden.
So können Sie tun:
import os
print(os.environ.get('SUDO_UID'))
Dann müssen Sie change the file ownership:
os.chown("path/to/file", uid, gid)
Wenn wir es zusammen:
import os
uid = int(os.environ.get('SUDO_UID'))
gid = int(os.environ.get('SUDO_GID'))
os.chown("path/to/file", uid, gid)
Natürlich, werden Sie will es als Funktion, weil es bequemer ist, also:
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"""
# first, create the file and close it immediatly
open(path, 'a').close()
# then fix the ownership
fix_ownership(path)
# open the file and return it
return open(path, mode)
Verbrauch:
# If you just want to fix the ownership of a file without opening it
fix_ownership("myfile.txt")
# if you want to create a file with the correct rights
myfile = get_file(path)
EDIT: Aktualisiert meine Antwort dank @Basilevs, @ Robᵩ und @ 5gon12eder
'chown' es, nachdem Sie es erstellen. –
ich will es als reale Benutzer öffnen, reagardless, wer das ist ... nicht etwas hart codiert – ABR
Sie können den aktuellen Benutzer und chown zu, die bestimmen. –