Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 312
Phil Boltt Avatar asked Dec 22 '22 04:12

Phil Boltt


2 Answers

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

like image 141
SamB Avatar answered Jan 05 '23 15:01

SamB


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

like image 37
Ignacio Vazquez-Abrams Avatar answered Jan 05 '23 15:01

Ignacio Vazquez-Abrams