Chan Kim Chan Kim - 3 months ago 9
Python Question

Why os.path.dirname returns /usr/local/bin not the python script's path?

For another simple test, I made this code (file name is test3.py) and I put in in /home/ckim/python/test3 directory.

import os.path as osp
import sys

def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)

this_dir = osp.dirname(__file__)

lib_path = osp.join(this_dir, 'lib')
add_path(lib_path)

from pack1.ppp import ppp

if __name__ == '__main__':
print ('starting main..')
ppp()


When I run the code,
this_dir
value gives me
/usr/local/dir
when I expected it to be
/home/ckim/python/test3
. What is the problem?

Answer

Use os.path.realpath as well to make it work:

this_dir = osp.dirname(osp.realpath(__file__))

os.getcwd() might also solve your problem.