使用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"""
open(path, 'a').close()
fix_ownership(path)
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的帮助,我更新了我的答案。
root
是您的进程的真实用户ID。非root
身份是某个父(或祖父)进程的真实用户ID。 - Robᵩsudo
man页面的介绍,“当sudo执行一个命令时...通常情况下,真实和有效的用户ID以及组ID将被设置为目标用户所匹配的ID。” - Robᵩ