Reputation: 23
I couldn't find a solution to my question, I hope it's not a duplicate and that someone can help me.
I have a python script that can be called by bash scripts and I cannot retrieve the directory of the bash script.
I cannot use os.getcwd ( cause i won't call the bash script from its own directory ).
I cannot setup an custom env variable in the bash script, because i do not have control over the bashscript ( in fact there are 2 bash scripts and i have control over only one )
Moreover the bash script can be started by another bashscript, but i only want the last one that called my python script.
thanks
Edit: summarized question:
-> I want to retrieve in my python script the directory of the bash script that "called me"
Upvotes: 2
Views: 852
Reputation: 166
you can do it by getting the father process which running your python script.
try using psutil for that.
update: so here is more specific solution: first of all get the parent process like i show above.
now there are two options:
in case of absolute path you should use the output of cmdline and everything would be great.
in case of relative path, take the relative path from cmdline, and combine it with the output of cwd from absolute path.
example:
Upvotes: 2
Reputation: 1155
I think it won't be possible from inside the python script. It has to be driven by the bash script calling it, either directly or indirectly.
You can use the way mentioned in the question @Benjamin posted in comments, to find the bash scripts' path in the bash script itself, and then just pass it as an argument to your python script, or set an env variable.
I know you don't want to do it. But other approaches like psutil
will also be dependent on how the parent script was run. If you can ensure that the parent script can be run using its absolute path, but not how it calls your script, then @SocketPlayer's answer on this question will be suitable for you. following works on my macbook
import psutil
calling_script = psutil.Process().parent()
print ("calling_script", calling_script.cmdline()[1])
Inside the python script: (A sample of passing it as cmd argument)
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'callers_path', help="the shell script calling this python script must provide it's path here", type=str)
args = parser.parse_args()
callers_path = args.callers_path
print ("callers_path", callers_path)
Upvotes: 2