Python: how to find the path to a script to run a python script

Say I have a python script in homedir/codes/py/run.py I also have a bash script at homedir/codes/run.sh This bash script works run.pyon python py/run.py.

The thing is, I need to find out the run.pypath to the calling script run.sh. If run.shlaunched from its own directory, I can just use os.getcwd(). But run.shyou can, in principle, run from anywhere, and then os.getcwd()return the path to where run.shFROM is running, and not the actual location run.sh.

Example:

  • Q homedir/codes: ./run.shos.getcwd()returnshomedir/codes
  • Q homedir: ./codes/run.shos.getcwd()returnshomedir

But I want homedir/codesno matter how called run.sh. Is it possible?

+3
source share
2 answers

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

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

Now pass this variable as the last argument to the python script. You can get an argument from python like:

sys.argv[-1]
+3
source

you can get the absolute path with:

os.path.join(os.path.abspath(os.curdir))
+3
source

Source: https://habr.com/ru/post/1753482/


All Articles