Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to find path to the script running a python script

Tags:

python

path

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?

like image 271
Eskil Avatar asked Dec 06 '25 00:12

Eskil


2 Answers

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]
like image 154
fmark Avatar answered Dec 07 '25 15:12

fmark


you can get the absolute qualified path with:

os.path.join(os.path.abspath(os.curdir))
like image 40
bharling Avatar answered Dec 07 '25 15:12

bharling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!