How to find the name of a script file executed when it is executed from a symbolic link to linux

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

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

#!/usr/bin/python import sys print sys.argv[0] print __file__ 

and I create this symbolic link

 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

+4
source share
3 answers

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

+7
source

os.readlink() resolve the symbolic link and os.path.islink() will tell you if this is a symbolic link in the first place.

+3
source

I believe that you will need to check if the file is a symbolic link, and if so, where it is connected. For instance...

 try: print os.readlink(__file__) except: print "File is not a symlink" 
0
source

Source: https://habr.com/ru/post/1305609/


All Articles