Where is module being imported from?

前端 未结 8 1340
余生分开走
余生分开走 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:23

    Also, if you have a function/class f from a module m you can get the path of the module using the module inspect

    import inspect
    from m import f
    
    print inspect.getmodule(f)
    
    0 讨论(0)
  • 2020-12-07 20:23

    This is how I do it:

    print(module_name.__path__)
    
    0 讨论(0)
  • 2020-12-07 20:28

    Try my_module.__file__ to find out where it is from. If you get an AttributeError, it is probably not a Python source (.py) file.

    0 讨论(0)
  • 2020-12-07 20:30

    If you want to see where a module is stored, for example setuptools, type in shell:

    $ python -c "import setuptools; print(setuptools.__file__)"

    0 讨论(0)
  • 2020-12-07 20:32

    Other answers are OK, but if you want to tell it from inside the imported module then do

    print "I was imported from %s" % __file__
    
    0 讨论(0)
  • 2020-12-07 20:33

    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.

    0 讨论(0)
提交回复
热议问题