Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do file permissions show different in Python and bash?

From Python:

>>> import os
>>> s = os.stat( '/etc/termcap')
>>> print( oct(s.st_mode) )
**0o100444**

When I check through Bash:

$ stat -f "%p %N" /etc/termcap
**120755** /etc/termcap

Why does this return a different result?

like image 643
FlowRaja Avatar asked Apr 07 '16 20:04

FlowRaja


People also ask

How do I check permissions on a file in Python?

To check whether current process has permissions on a certain file, we could use os. access which is based on the access system call. It uses real-uid instead of the effective uid of the calling process.

How do you change permissions on a file in Python?

To change file permissions, you can use os. chmod(). You can bitwise OR the following options to set the permissions the way you want. These values come from the stat package: Python stat package documentation.


1 Answers

This is because your /etc/termcap is a symlink. Let me demonstrate this to you:

Bash:

$ touch bar
$ ln -s bar foo
$ stat -f "%p %N" foo
120755 foo
$ stat -f "%p %N" bar
100644 bar

Python:

>>> import os
>>> oct(os.stat('foo').st_mode)
'0100644'
>>> oct(os.stat('bar').st_mode)
'0100644'
>>> oct(os.lstat('foo').st_mode)
'0120755'
>>> oct(os.lstat('bar').st_mode)
'0100644'

Conclusion, use os.lstat instead of os.stat

like image 193
DevLounge Avatar answered Nov 15 '22 16:11

DevLounge