sudo के साथ अपनी स्क्रिप्ट चल रहा है मतलब है कि आप रूट के रूप में इसे चलाने के। तो यह सामान्य है कि आपकी फाइल रूट के स्वामित्व में है।
आप जो भी कर सकते हैं वह फ़ाइल के स्वामित्व को बनाए जाने के बाद बदलना है। ऐसा करने के लिए, आपको यह जानने की जरूरत है कि कौन सा उपयोगकर्ता सुडो चलाता है। सौभाग्य से, SUDO_UID
पर्यावरण चर है जो आप सूडो का उपयोग करते समय सेट किया गया है।
तो, आप कर सकते हैं:
os.chown("path/to/file", uid, gid)
यदि हम यह एक साथ रखा:
import os
print(os.environ.get('SUDO_UID'))
उसके बाद, आप change the file ownership की जरूरत
import os
uid = int(os.environ.get('SUDO_UID'))
gid = int(os.environ.get('SUDO_GID'))
os.chown("path/to/file", uid, gid)
बेशक
लिए, आप इसे एक समारोह के रूप में चाहते हैं, क्योंकि यह अधिक सुविधाजनक है, इसलिए:
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)
उपयोग:
# 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)
संपादित करें: @Basilevs करने के लिए अपने जवाब के लिए धन्यवाद अपडेट किया गया, @ Robᵩ और @ 5gon12eder
'यह chown' बनाने के बाद। –
मैं इसे वास्तविक उपयोगकर्ता के रूप में खोलना चाहता हूं, यह किसके बारे में है ... यह कुछ कठिन कोड नहीं है – ABR
आप वर्तमान उपयोगकर्ता को निर्धारित कर सकते हैं और उस पर दिखाया जा सकता है। –