Where is module being imported from?

前端 未结 8 1341
余生分开走
余生分开走 2020-12-07 19:57

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
impo         


        
相关标签:
8条回答
  • 2020-12-07 20:39

    I've written a simple script so I have the command pywhich that allows me to find where a Python module comes from. It doesn't work for some builtins like sys which doesn't have a \__file__ attribute.

    This can be run from a Linux command line to find where a python script run in the current environment will get a module from, for example:

    % pywhich os


    #! /usr/bin/env python
    def pywhich(module_name):
        module = __import__(module_name, globals(), locals(), [], 0)
        return module.__file__
    
    if __name__ == "__main__":
        import sys
        print(pywhich(sys.argv[1]))
    
    0 讨论(0)
  • 2020-12-07 20:45

    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__))
    
    0 讨论(0)
提交回复
热议问题