Where is module being imported from?

前端 未结 8 1403
余生分开走
余生分开走 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]))
    

提交回复
热议问题