In interactive python I’d like to import a module that is in, say,
C:\Modules\Module1\module.py
What I’ve been able to do is to create an empty
C:\Modules\Module1\__init__.py
and then do:
>>> import sys
>>> sys.path.append(r'C:\Modules\Module1')
>>> import module
And that works, but I’m having to append to sys.path, and if there was another file called module.py that is in the sys.path as well, how to unambiguously resolve to the one that I really want to import?
Is there another way to import that doesn’t involve appending to sys.path?
EDIT: Here’s something I’d forgotten about: Is this correct way to import python scripts residing in arbitrary folders? I’ll leave the rest of my answer here for reference.
There is, but you’d basically wind up writing your own importer which manually creates a new module object and uses
execfileto run the module’s code in that object’s “namespace”. If you want to do that, take a look at the mod_python importer for an example.For a simpler solution, you could just add the directory of the file you want to import to the beginning of
sys.path, not the end, like so:You shouldn’t need to create the
__init__.pyfile, not unless you’re importing from within a package (so, if you were doingimport package.modulethen you’d need__init__.py).