How to retrieve a module's path?

后端 未结 20 1738
无人及你
无人及你 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: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
    
    

    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.

提交回复
热议问题