esecuzione dello script con sudo significa che si esegue come root. Quindi è normale che il tuo file sia di proprietà di root.
Quello che si potrebbe fare è modificare la proprietà del file dopo che è stato creato. Per fare ciò, è necessario sapere quale utente esegue sudo. Fortunatamente, esiste una variabile di ambiente SUDO_UID
impostata quando si utilizza sudo.
Quindi, si può fare:
import os
print(os.environ.get('SUDO_UID'))
Quindi, è necessario change the file ownership:
os.chown("path/to/file", uid, gid)
Se mettiamo insieme:
import os
uid = int(os.environ.get('SUDO_UID'))
gid = int(os.environ.get('SUDO_GID'))
os.chown("path/to/file", uid, gid)
Naturalmente, ti Lo voglio come una funzione, perché è più conveniente, quindi:
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)
Usage:
# 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: aggiornato la mia risposta grazie a @Basilevs, @ Robᵩ e @ 5gon12eder
'chown' che dopo averlo creato. –
voglio che si apra come l'utente reale, senza reagenti di chi è ... non qualcosa di codificato – ABR
È possibile determinare l'utente corrente e chown a quello. –