Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when you are in a symbolic link

Tags:

python

How to know, in Python, that the directory you are in is inside a symbolic link ?

I have a directory /tmp/foo/kiwi

I create a symlink /tmp/bar pointing to /tmp/foo

I enter into /tmp/bar/kiwi

the linux command pwd tells me I'm in /tmp/bar/kiwi, which is correct.

The python command prompt tells me I'm in /tmp/foo/kiwi:

Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getcwd()
'/tmp/foo/kiwi'

Is there a way, in Python, to get the directory I'm really in ?

like image 517
Oli Avatar asked Mar 01 '23 02:03

Oli


2 Answers

If you don't find anything else, you can use

os.getenv("PWD")

It's not really a portable python method, but works on POSIX systems. It gets the value of the PWD environment variable, which is set by the cd command (if you don't use cd -P) to the path name you navigated into (see man cd) before running the python script. That variable is not altered by python, of course. So if you os.chdir somewhere else, that variable will retain its value.

Anyway, as a side node, /tmp/foo/kiwi is the directory you are in. I'm not sure whether anything apart from the shell knows that you've really navigated through another path into that place, actually :)

like image 98
Johannes Schaub - litb Avatar answered Mar 11 '23 05:03

Johannes Schaub - litb


If your symlink is set up in the way you state, then /tmp/foo/kiwi is the directory that you're really in. /tmp/bar/kiwi is just another way to get to the same place.

Note that the shell command pwd -P will give you the physical path of the current directory. In your case, the shell is remembering that you got where you are through the bar symlink, so it tell you that you are in /tmp/bar/kiwi.

like image 33
Greg Hewgill Avatar answered Mar 11 '23 06:03

Greg Hewgill