2017-10-21 74 views
0

我想递归地改变一个目录的组名,我使用os.chown()来做到这一点。但是我在os.chown()中找不到像(chgrp -R)这样的递归标志。在python中是否有任何等效的chgrp -R?

+0

正确。手动递归。 –

+0

所以我必须os.walk并使用os.chown()更改每个文件组? –

+0

@FujiClado是的, –

回答

1

写了一个函数来执行chgrp命令-R

def chgrp(LOCATION,OWNER,recursive=False): 

    import os 
    import grp 

    gid = grp.getgrnam(OWNER).gr_gid 
    if recursive: 
     if os.path.isdir(LOCATION): 
     os.chown(LOCATION,-1,gid) 
     for curDir,subDirs,subFiles in os.walk(LOCATION): 
      for file in subFiles: 
      absPath = os.path.join(curDir,file) 
      os.chown(absPath,-1,gid) 
      for subDir in subDirs: 
      absPath = os.path.join(curDir,subDir) 
      os.chown(absPath,-1,gid) 
     else: 
     os.chown(LOCATION,-1,gid) 
    else: 
    os.chown(LOCATION,-1,gid) 
+0

为什么如此复杂,只能将chgpr -R传递给shell? – mfnalex

2

为什么不把你的命令传递给shell?

os.system("chgrp -R ...") 
相关问题