Hi,
I symlinked a pth file to the site-packages directory of my virtualenv. Then I want to obtain the realpath of this pth file from within it with python code.
But it seems the python code used in this file must only be one-line python code and it doesn't know the meaning of 'os.path.realpath(__file__)'
Any hints for this problem?
Regards
import os
os.chdir(os.path.abspath(os.path.dirname(__file__))) # Make sure starting dir is OK
print(os.path.realpath('CreateDict.py'))
This doesn't solve my problem, I want to obtain the directory from where the pth file is symlinked to the site-packages directory, instead of the site-packages directory itself. Say, if I symlinked the the file with
ln -s ~/test.pth /path/to/site-packages/
And there are the following the lines in this pth file:
import os; os.chdir(os.path.abspath(os.path.dirname(__file__))); print(os.path.realpath('CreateDict.py'))
This will print the following twice:
$ python
/home/werner/.pyenv/versions/3.8.1/lib/python3.8/CreateDict.py
/home/werner/.pyenv/versions/3.8.1/lib/python3.8/CreateDict.py
Python 3.8.1 (default, Mar 11 2020, 09:08:36)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
But I want the obtain the directory of $HOME.
Regards
from os.path import expanduser
home = expanduser("~")
@
anbu23 I just use HOME as a simple example, in fact the pth file is not in that directory.
$ ln -s /path/to/test.pth /path/to/site-packages/
In this general case, I want to obtain the source path of the pth file use python code from within it.
Regards
print(os.path.abspath('test.pth'))
No, it cannot do the trick.
You cannot use __file__. It will always return the current script name, as will sys.argv[0]
you must use actual file name:
import os
import sys
def show_symlink():
# Set current path to that of script
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# get address of self
print(f"value of __file__: {__file__}")
print(f"value of sys.argv[0]: {sys.argv[0]}")
print(f"Current working directory: {os.getcwd()}")
print(f"using realpath: {os.path.realpath('CreateDict.py')}")
print(f"using readlink: {os.readlink('CreateDict.py')}")
show_symlink()
will give:
Output:
value of __file__: .../projects/T-Z/T/Trailmapper/Florida2020/src/TestArea/ShowSympath.py
value of sys.argv[0]: .../projects/T-Z/T/Trailmapper/Florida2020/src/TestArea/ShowSympath.py
Current working directory: .../projects/T-Z/T/Trailmapper/Florida2020/src/TestArea
using realpath: .../projects/T-Z/T/Trailmapper/src/CreateDict.py
using readlink: ../CreateDict.py
As you can see,
print(f"using realpath: {os.path.realpath('CreateDict.py')}")
gives the full directory of what the symlink points to
As does
print(f"using readlink: {os.readlink('CreateDict.py')}")
albeit that this is a relative path (exactly as originally defined with the ln command)
CreateDict.py resides one directory above TestArea (in the src Directiry), the symlink is in TestArea
This works properly.