views:

55

answers:

3

Hi,

If I have a python script that is executed via a symlink, is there a way that I can find the path to the script rather than the symlink? I've tried using the methods suggested in this question, but they always return the path to the symlink, not the script.

For example, when this is saved as my "/usr/home/philboltt/scripts/test.py" :

#!/usr/bin/python

import sys

print sys.argv[0]
print __file__

and I then create this symlink

ln -s /usr/home/philboltt/scripts/test.py /usr/home/philboltt/test

and execute the script using

/usr/home/philboltt/test

I get the following output:

/usr/home/philboltt/test
/usr/home/philboltt/test

Thanks! Phil

+2  A: 

os.readlink() will resolve a symlink, and os.path.islink() will tell you if it's a symlink in the first place.

Ignacio Vazquez-Abrams
Cool, but how do you check if something is a symlink? What will os.readlink() return if pointed to a non-link? I suppose this is not hard to test.
Hamish Grubijan
What about race conditions? It could get replaced by a symlink after you check but before you call readlink...
SamB
+4  A: 

You want the os.path.realpath() function.

SamB
That does the trick! Thanks Sam!
Phil Boltt
A: 

I believe you will need to check if the file is a symlink, and if so, get where it is linked to. For example...

try:
    print os.readlink(__file__)
except:
    print "File is not a symlink"
Josh Braegger
os.path.realpath(__file__) is the better answer your question actually
Josh Braegger