How to retrieve a module's path?

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

    As the other answers have said, the best way to do this is with __file__ (demonstrated again below). However, there is an important caveat, which is that __file__ does NOT exist if you are running the module on its own (i.e. as __main__).

    For example, say you have two files (both of which are on your PYTHONPATH):

    #/path1/foo.py
    import bar
    print(bar.__file__)
    

    and

    #/path2/bar.py
    import os
    print(os.getcwd())
    print(__file__)
    

    Running foo.py will give the output:

    /path1        # "import bar" causes the line "print(os.getcwd())" to run
    /path2/bar.py # then "print(__file__)" runs
    /path2/bar.py # then the import statement finishes and "print(bar.__file__)" runs
    

    HOWEVER if you try to run bar.py on its own, you will get:

    /path2                              # "print(os.getcwd())" still works fine
    Traceback (most recent call last):  # but __file__ doesn't exist if bar.py is running as main
      File "/path2/bar.py", line 3, in 
        print(__file__)
    NameError: name '__file__' is not defined 
    

    Hope this helps. This caveat cost me a lot of time and confusion while testing the other solutions presented.

提交回复
热议问题