shutil的文档告诉我:
即使是更高级别的文件复制功能(shutil.copy(),shutil.copy2())也无法复制所有文件元数据。在POSIX平台上,这意味着文件所有者和组以及ACL都会丢失
如果我需要在python中复制文件,如何保留文件所有者和组?
该进程以root身份在linux上运行。
更新:我们不使用ACL。我们只需要保留使用tar和rsync等工具保存的东西。
您可能可以使用os.stat
来获取guid
和uid
,然后在使用this answer应对后重置uid
和guid
。
您可以使用os.chown
模块:
subprocess
我是这样做的:
from subprocess import Popen
p = Popen(['cp','-p','--preserve',src,dest])
p.wait()
请参阅import os
import stat
import shutil
def copyComplete(source, target):
# copy content, stat-info (mode too), timestamps...
shutil.copy2(source, target)
# copy owner and group
st = os.stat(source)
os.chown(target, st[stat.ST_UID], st[stat.ST_GID])
关于Keeping fileowner and permissions after copying file in C本身如何做到这一点,然后只是复制它的逻辑。 Python具有cp
模块中提到的所有系统调用。
我建议你使用操作系统和子进程模块。这只适用于Unix,但它应该运行良好。使用os.fchown更改文件所有权,使用subprocess.Popen()将ls -l管道传输到变量中以读取所有权。对于一个文件,权限阅读器将如下所示:
os
对于uid setter(只是os函数的包装器):
import os
import subprocess
def readfile(filepath):
process = subprocess.Popen(["ls","-l"],stdout=subprocess.PIPE)
output = process.communicate()[0]
output = output.split()
return (output[0],output[1]) #insert into this tuple the indexing for the words you want from ls -l
作为@Thom Wiggers的回答
演示代码:
def setuid(filepath,uid,gid):
os.chown(filepath,uid,gid)
检查除外:
import os
st = os.stat(src_path)
os.chown(dst_path, st.st_uid, st.st_gid)