2

I have a caller script /home/x/a/a.py that uses module /home/x/b.py

Inside b.py, I want to know the full path of the caller script, i.e. /home/x/a/a.py. How can I get that?

I looked at How to get the caller script name but it only gave me the script name which is a.py

abisko
  • 663
  • 8
  • 21
  • Do you want to get the "caller" when calling a method or when importing the module? – Iain Shelvington Sep 17 '19 at 02:45
  • you can `pass` it as a variable when you call `b.py`, but other than that I don't think there is a practical way for `b.py` to know who called it. – monkut Sep 17 '19 at 02:52
  • Possible duplicate of [How do I get the path and name of the file that is currently executing?](https://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing) in particular [this answer](https://stackoverflow.com/a/31867043/1467082) looks promising. – David Zemens Sep 17 '19 at 02:53

1 Answers1

2

A very simplified version of what happens (for the CPython interpreter):

Every time a method is called in Python a "frame" is added to the stack, after a method returns something the interpreter pops the last frame from the stack and continues execution of the previous frame with the return value injected in place of the method call

To get the previous frame you can call sys._getframe(1) (0 would get the current frame, 1 gets the previous frame). The inspect module provides a method getframeinfo that returns some useful information about the frame including the filename. This can be combined like so

import inspect
import sys

def foo():
    print('Called from', inspect.getframeinfo(sys._getframe(1)).filename)

Whenever foo is called it will print the filename of the calling method

Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
  • This only gives me the filename of the caller, but I need the full path. Is it possible? – abisko Sep 17 '19 at 13:06
  • 1
    This will give you a relative path to your working directory. You should be able to combine those to get the absoulte path: `import os` `os.path.join(os.getcwd(), filename)` – EzPizza Mar 08 '21 at 13:32