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 a module's path in python?
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 a module's path in python?
I will try tackling a few variations on this question as well:
(Some of these questions have been asked on SO, but have been closed as duplicates and redirected here.)
Caveats of Using
__file__
For a module that you have imported:
will return the absolute path of the module. However, given the folowing script foo.py:
Calling it with 'python foo.py' Will return simply 'foo.py'. If you add a shebang:
and call it using ./foo.py, it will return './foo.py'. Calling it from a different directory, (eg put foo.py in directory bar), then calling either
or adding a shebang and executing the file directly:
will return 'bar/foo.py' (the relative path).
Finding the directory
Now going from there to get the directory,
os.path.dirname(__file__)
can also be tricky. At least on my system, it returns an empty string if you call it from the same directory as the file. ex.will output:
In other words, it returns an empty string, so this does not seem reliable if you want to use it for the current file (as opposed to the file of an imported module). To get around this, you can wrap it in a call to abspath:
which outputs something like:
Note that abspath() does NOT resolve symlinks. If you want to do this, use realpath() instead. For example, making a symlink file_import_testing_link pointing to file_import_testing.py, with the following content:
executing will print absolute paths something like:
file_import_testing_link -> file_import_testing.py
Using inspect
@SummerBreeze mentions using the inspect module.
This seems to work well, and is quite concise, for imported modules:
obediently returns the absolute path. However for finding the path of the currently executing script, I did not see a way to use it.
you can just import your module then hit its name and you'll get its full path
There is
inspect
module in python.Official documentation
Example:
So I spent a fair amount of time trying to do this with py2exe The problem was to get the base folder of the script whether it was being run as a python script or as a py2exe executable. Also to have it work whether it was being run from the current folder, another folder or (this was the hardest) from the system's path.
Eventually I used this approach, using sys.frozen as an indicator of running in py2exe:
Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do
You can also try
To get the directory to look for changes.