How to retrieve a module's path?

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

    I'd like to contribute with one common scenario (in Python 3) and explore a few approaches to it.

    The built-in function open() accepts either relative or absolute path as its first argument. The relative path is treated as relative to the current working directory though so it is recommended to pass the absolute path to the file.

    Simply said, if you run a script file with the following code, it is not guaranteed that the example.txt file will be created in the same directory where the script file is located:

    with open('example.txt', 'w'):
        pass
    

    To fix this code we need to get the path to the script and make it absolute. To ensure the path to be absolute we simply use the os.path.realpath() function. To get the path to the script there are several common functions that return various path results:

    • os.getcwd()
    • os.path.realpath('example.txt')
    • sys.argv[0]
    • __file__

    Both functions os.getcwd() and os.path.realpath() return path results based on the current working directory. Generally not what we want. The first element of the sys.argv list is the path of the root script (the script you run) regardless of whether you call the list in the root script itself or in any of its modules. It might come handy in some situations. The __file__ variable contains path of the module from which it has been called.


    The following code correctly creates a file example.txt in the same directory where the script is located:

    filedir = os.path.dirname(os.path.realpath(__file__))
    filepath = os.path.join(filedir, 'example.txt')
    
    with open(filepath, 'w'):
        pass
    

提交回复
热议问题