Walking Wiki
Walking Wiki

Reputation: 699

How do I find the name of the file that is the importer, within the imported file?

How do I find the name of the file that is the "importer", within the imported file?

If a.py and b.py both import c.py, is there anyway that c.py can know the name of the file importing it?

Upvotes: 5

Views: 1092

Answers (4)

Dave
Dave

Reputation: 385

Use

sys.path[0]

returns the path of the script that launched the python interpreter. If you can this script directly, it will return the path of the script. If the script however, was imported from another script, it will return the path of that script.

See Python Path Issues

Upvotes: 3

S.Lott
S.Lott

Reputation: 391854

That's why you have parameters.

It's not the job of c.py to determine who imported it.

It's the job of a.py or b.py to pass the variable __name__ to the functions or classes in c.py.

Upvotes: 2

Steven Kryskalla
Steven Kryskalla

Reputation: 14649

It can be done by inspecting the stack:

#inside c.py:
import inspect
FRAME_FILENAME = 1
print "Imported from: ", inspect.getouterframes(inspect.currentframe())[-1][FRAME_FILENAME]
#or:
print "Imported from: ", inspect.stack()[-1][FRAME_FILENAME]

But inspecting the stack can be buggy. Why do you need to know where a file is being imported from? Why not have the file that does the importing (a.py and b.py) pass in a name into c.py? (assuming you have control of a.py and b.py)

Upvotes: 1

Phil
Phil

Reputation: 4867

In the top-level of c.py (i.e. outside of any function or class), you should be able to get the information you need by running

import traceback

and then examining the result of traceback.extract_stack(). At the time that top-level code is run, the importer of the module (and its importer, etc. recursively) are all on the callstack.

Upvotes: 2

Related Questions