는 루트로 실행 의미한다. 따라서 파일은 루트가 소유하고있는 것이 정상입니다.
파일을 만든 후에 소유권을 변경할 수 있습니다. 이렇게하려면 sudo를 실행하는 사용자를 알아야합니다. 다행히 sudo를 사용할 때 설정되는 SUDO_UID
환경 변수가 있습니다.
그래서, 당신은 할 수 있습니다 :
import os
print(os.environ.get('SUDO_UID'))
을 그런 다음 change the file ownership 필요 :
os.chown("path/to/file", uid, gid)
우리가 함께 넣어 경우 : 물론
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)
편집 : Robᵩ @ @Basilevs에 대한 내 대답 덕분에 업데이트하고 @ 당신이 그것을 만든 후
는'를 chown' 5gon12eder. –
내가 실제 사용자로 열길 원하는데, 누가 이건 ... 하드 코딩되지 않은 것입니까? – ABR
현재 사용자를 확인하고 그 사용자에게 chown 할 수 있습니다. –