3

Lets say i have a python script at homedir/codes/py/run.py I also have a bash script at homedir/codes/run.sh This bash script runs run.py by python py/run.py.

The thing is that i need to be able to find out, in run.py, the path to the calling script run.sh. If run.sh is run from its own directory, i can just use os.getcwd(). But run.sh can in principle be run from anywhere, and then os.getcwd() will return the path to where run.sh is run FROM, and not the actual location of run.sh.

ex:

  • At homedir/codes: ./run.sh -> os.getcwd() returns homedir/codes
  • At homedir: ./codes/run.sh -> os.getcwd() returns homedir

But i want homedir/codes no matter how run.sh is called. Is this possible?

3
  • What should happen if the Python script is run directly from an interactive shell, not from run.sh? Commented Jul 7, 2010 at 7:59
  • If the bash scripts contains nothing but python py/run.py, it must be run from homedir/codes otherwise py/run.py wouldn't be found. So your question is not complete. Commented Jul 7, 2010 at 7:59
  • Oh, sorry i didn't think this through enough. I guess i'll have to assume run.sh is run from its own directory, or else the relative path to run.py won't work (as you say). Commented Jul 7, 2010 at 8:16

2 Answers 2

3

To get the absolute path of the current script in bash, do:

SCRIPT=$(readlink -f "$0")

Now, pass that variable as the last argument to the python script. You can get the argument from python as:

sys.argv[-1]
Sign up to request clarification or add additional context in comments.

3 Comments

Another way of getting the current directory of the running bash script (with dirname command within backticks): SCRIPT='dirname $0'
This mostly works, but is nonportable, see mywiki.wooledge.org/BashFAQ/028. $0, like all parameters, should always be quoted.
If you don't want to pass parameters, it should also be possible to set the directory you want in the shell wrapper.
3

you can get the absolute qualified path with:

os.path.join(os.path.abspath(os.curdir))

3 Comments

This isn't want the OP wants.
It is what I was Googling for :-)
This same as pwd -P This is not the path of the script. This is the path of the user.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.