Search code examples
pythonchmodstat

In Python's stat module, when I print stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO, why do I get 511 instead of 777?


The octal integer to set all permissions as active is 0777. Then why do I get 511 when I print the string values of the same?


Solution

  • 0777 is an octal representation.

    In other word, 0777 = 7 * (8**2) + 7 * (8**1) + 7 * (8**0)

    >>> 0777
    511
    >>> 7 * (8**2) + 7 * (8**1) + 7 * (8**0)
    511
    
    >>> 0777 == 777
    False
    

    If you want to get octal representation of a number, use oct, % operator or str.foramt with appropriate format specifier:

    >>> oct(511)
    '0777'
    >>> '%o' % 511
    '777'
    >>> '{:o}'.format(511)
    '777'