Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

python - Where is module being imported from?

Assuming I have two Python modules and path_b is in the import path:

# file: path_b/my_module.py
print "I was imported from ???"

#file: path_a/app.py
import my_module

Is it possible to see where the module is imported from? I want an output like "I was imported from path_a/app.py", if I start app.py (because I need the file name).

Edit: For better understanding; I could write:

# file: path_b/my_module.py
def foo(file):
    print "I was imported from %s" % file

#file: path_a/app.py
import my_module
my_module.foo(__file__)

So the output would be:

$> python path_app.py
I was imported from path_a/app.py
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

>>> import my_module
>>> my_module.__file__
'/Users/myUser/.virtualenvs/foobar/lib/python2.7/site-packages/my_module/__init__.pyc'

Edit

In that case write into the __init__.py file of your module:

print("%s: I was imported from %s" %(__name__, __file__))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...