2017-10-21 52 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 ...") 
相關問題