755 -> rwxr-xr-x

Es gibt keine fertige Funktion, um aus einer per os.stat()[stat.ST_MODE] gewonnenen Zahl die chmod-typische symbolische Notation (z.B. rwxr-xr-x für 0755) zu generieren.

Hier sind ein paar Varianten, die die Konvertierung übernehmen:

Die Kurzform

   1 import os
   2 
   3 def symbolic_notation(mode):
   4     return ''.join(
   5         mode & 0400 >> i and x or '-' for i, x in enumerate('rwxrwxrwx')
   6     )
   7 
   8 print symbolic_notation(os.stat('blub').st_mode)

Auseinandergezogen

Derselbe Code von oben, nur "auseinandergezogen":

   1 import os
   2 
   3 def symbolic_notation(mode):
   4     result = []
   5     for i, x in enumerate('rwxrwxrwx'):
   6         m = mode & 0400 >> i
   7         symbol = m and x or '-'
   8         result.append(symbol)
   9 
  10     return ''.join(result)
  11 
  12 print symbolic_notation(os.stat('blub').st_mode)

Einfache dict-Variante

   1 CHMOD_TRANS_DATA = (
   2     u"---", u"--x", u"-w-", u"-wx", u"r--", u"r-x", u"rw-", u"rwx",
   3 )
   4 def symbolic_notation(mode):
   5     mode = mode & 0777 # strip "meta info"
   6     mode_string = u"%o" % mode
   7 
   8     return u''.join(CHMOD_TRANS_DATA[int(num)] for num in mode_string)
   9 
  10 print symbolic_notation(os.stat('blub').st_mode)

Passende Diskussion dazu, dort sind noch andere Lösungen:

755 -> rwxr-xr-x (last edited 2010-04-05 16:30:50 by JensDiemer)