Chan Kim Chan Kim -4 years ago 167
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 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')

from pack1.ppp import ppp

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

When I run the code,
value gives me
when I expected it to be
. What is the problem?

Answer Source

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

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

os.getcwd() might also solve your problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download