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

3
  • Do you want to get the "caller" when calling a method or when importing the module? Commented Sep 17, 2019 at 2: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. Commented Sep 17, 2019 at 2:52
  • Possible duplicate of How do I get the path and name of the file that is currently executing? in particular this answer looks promising. Commented Sep 17, 2019 at 2:53

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

This only gives me the filename of the caller, but I need the full path. Is it possible?
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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.