How to retrieve a module's path?

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

    If the only caveat of using __file__ is when current, relative directory is blank (ie, when running as a script from the same directory where the script is), then a trivial solution is:

    import os.path
    mydir = os.path.dirname(__file__) or '.'
    full  = os.path.abspath(mydir)
    print __file__, mydir, full
    

    And the result:

    $ python teste.py 
    teste.py . /home/user/work/teste
    

    The trick is in or '.' after the dirname() call. It sets the dir as ., which means current directory and is a valid directory for any path-related function.

    Thus, using abspath() is not truly needed. But if you use it anyway, the trick is not needed: abspath() accepts blank paths and properly interprets it as the current directory.

提交回复
热议问题