0

Getting the file system path of a python module by module name is easy if the module exists. For example like this:

importlib.machinery.PathFinder.find_module('my.module').path

But when the module does not exist, how can I still get the theoretical path that would be used to check whether the module exists?

Background: I want to watch the file system to be notified when a module (specified by module name like in an import statement) comes into existence.

1

1 Answer 1

1

Python uses it's own path variable to know where to look for modules. The path variable is a list containing all the directories where python looks for modules, going from start to finish. To get a look at it, you can use the sys module:

import sys

print(sys.path)

The first item in the list is the directory of the script, unless you're in an interactive session, in which case an empty string will be present, representing the current working directory.

Sign up to request clarification or add additional context in comments.

4 Comments

The empty string actually means the working directory. From the docs: "As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available, path[0] is the empty string, which directs Python to search modules in the current directory first." (added bold)
Well that's what I wanted to say. Thanks for clarifying it tho, I'll edit the answer.
Oh, that's still not quite right. Python will try to add "the directory containing the script", but if it can't, like in an interactive session, then it'll add the empty string.
Thanks. So, do I have to watch all the paths in sys.path for changes recursively? Maybe the paths could be made a bit more specific by appending to each of them the module name where the dots are replaced by /. Could that work? Is there a better way, maybe using an existing function from Python standard library? I want as little file watchers as possible, because of OS and memory limitations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.