1

I am writing a Python script that has to execute a shell script. In my GIT repo I have plans to commit both (Python program + Shell script) in same directory in my repo.

My issue is that when someone pulls out my code and wants to run my Python script from any relative / absolute location - I need to refer the shell script in the directory where my Python script resided.

I am not sure which one I should make use of

os.path.dirname(os.path.realpath(__file__))
OR
os.path.abspath(os.path.dirname(__file__))
OR
os.path.dirname(os.path.abspath(__file__))

If I run my python script in same directory it prints same values - even if I execute from a separate directory and run my script as mentioned below I still get same values:

 python ./test/test1/1.py

/x/home02/myhome/test/test1

If it so which one I should actually make use of? What is the difference in between each of them?

========== Updated =========

I created a symbolic link to my code like as mentioned below:

cd
ln -s /x/home02/myhome/test/test1/1.py 2.py

Now when I re-run my code as mentioned below -

cd
python 2.py
cd test
python ../2.py

I get the below output

/x/home02/myhome/test/test1
/x/home02/myhome
/x/home02/myhome

So I think the below one is the correct one as I am always getting the expected output:

os.path.dirname(os.path.realpath(__file__))
Programmer
  • 8,303
  • 23
  • 78
  • 162

3 Answers3

0

Well first you want the directory, so let's use os.path.dirname(...)

And os.path.abspath(__file__) should get you the path of the script, the difference between this and os.path.realpath() is the latter eliminates symbolic links, so not sure if you want that

So I'd use os.path.dirname(os.path.abspath(__file__))

bakkal
  • 54,350
  • 12
  • 131
  • 107
  • Please see my updated findings in my question .. thanks for giving the correct steps to resolve symbolic links protection in my code – Programmer Dec 24 '15 at 06:56
0

The difference between os.path.realpath and os.path.abspath is the former eliminates symbolic links whereas the latter be the absolute path of a symbolic link.

In this case, the order of os.path.dirname and abspath or realpath shouldn't matter -- It would only matter if the file you passed in didn't have a directory portion.

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

You should use absolute path with directory name of pathname, like this:

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Find the common pathname manipulations (os.path) documentation to find the difference between the usage here: https://docs.python.org/3/library/os.path.html

Sameer Mirji
  • 2,135
  • 16
  • 28