How to find the filename of a script being run when it is executed from a symlink on linux

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/" :


import sys

print sys.argv[0]
print __file__

and I then create this symlink

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

and execute the script using


I get the following output:


Thanks! Phil


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

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

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

    print os.readlink(__file__)
    print "File is not a symlink"

Need Your Help

Request big file stream failed with wcf rest

c# wcf streaming httpwebrequest

I have a REST GET API that is written using WCF library to return Stream of a specific requested file that is located on API server that hosts that web service application. The service works well i...