How can I find out what file is importing a particular file in python?
Consider the following example:
#a.py
import cmn
....
#b.py
import cmn
...
#cmn.py
#Here, I want to know which file (a.py or b.py)
#is importing this one.
#Is it possible to do this?
...
All the files a.py
, b.py
and cmn.py
are in the same directory.
Why do I want to do this?
In C/C++, they have include feature. What i want to do can illuminate by the C/C++ code.
//a.cpp
....
#define SOME_STUFF ....
#include "cmn.h"
//b.cpp
...
#define SOME_STUFF ....
#include "cmn.h"
//cmn.h
//Here, I'll define some functions/classes that will use the symbol define
//in the a.cpp or b.cpp
...
....code refer to the SOME_STUFF.....
In C/C++, we can use this method to reuse sourecode.
Now return to my python code.
When a.py import cmn.py, i hope to run cmn.py and the cmn.py will refer to the symbol defined in the a.py.
When b.py import cmn.py, i hope to run cmn.py and the cmn.py will refer to the symbol defined in the b.py.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…