Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is module being imported from?

Tags:

python

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 
like image 392
svenwltr Avatar asked Aug 22 '11 17:08

svenwltr


People also ask

How can I tell where Python is importing from?

Running "python -v"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built in modules.

How modules are imported?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

Where are imported modules stored in Python?

Usually in /lib/site-packages in your Python folder. (At least, on Windows.) You can use sys. path to find out what directories are searched for modules.


2 Answers

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__)) 
like image 122
Johannes Avatar answered Nov 07 '22 21:11

Johannes


There may be an easier way to do this, but this works:

import inspect  print inspect.getframeinfo(inspect.getouterframes(inspect.currentframe())[1][0])[0] 

Note that the path will be printed relative to the current working directory if it's a parent directory of the script location.

like image 23
Wooble Avatar answered Nov 07 '22 20:11

Wooble