使用 sudo 运行脚本意味着您以 root 身份运行它。所以你的文件归root所有是正常的。
您可以做的是在创建文件后更改文件的所有权。为此,您需要知道哪个用户运行 sudo。幸运的是,SUDO_UID
使用 sudo 时设置了一个环境变量。
所以,你可以这样做:
import os
print(os.environ.get('SUDO_UID'))
然后,您需要更改文件所有权:
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)
编辑:感谢@Basilevs、@Robᵩ 和@5gon12eder 更新了我的答案