How to retrieve a module's path?

后端 未结 20 1686
无人及你
无人及你 2020-11-22 05:34

I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.

How do I retrieve

相关标签:
20条回答
  • 2020-11-22 06:24

    Command Line Utility

    You can tweak it to a command line utility,

    python-which <package name>
    


    Create /usr/local/bin/python-which

    #!/usr/bin/env python
    
    import importlib
    import os
    import sys
    
    args = sys.argv[1:]
    if len(args) > 0:
        module = importlib.import_module(args[0])
        print os.path.dirname(module.__file__)
    

    Make it executable

    sudo chmod +x /usr/local/bin/python-which
    
    0 讨论(0)
  • 2020-11-22 06:25

    If you wish to do this dynamically in a "program" try this code:
    My point is, you may not know the exact name of the module to "hardcode" it. It may be selected from a list or may not be currently running to use __file__.

    (I know, it will not work in Python 3)

    global modpath
    modname = 'os' #This can be any module name on the fly
    #Create a file called "modname.py"
    f=open("modname.py","w")
    f.write("import "+modname+"\n")
    f.write("modpath = "+modname+"\n")
    f.close()
    #Call the file with execfile()
    execfile('modname.py')
    print modpath
    <module 'os' from 'C:\Python27\lib\os.pyc'>
    

    I tried to get rid of the "global" issue but found cases where it did not work I think "execfile()" can be emulated in Python 3 Since this is in a program, it can easily be put in a method or module for reuse.

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