views:

36

answers:

2

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?

+2  A: 

EDIT: Here's something I'd forgotten about: http://stackoverflow.com/questions/3137731/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 execfile to 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:

>>> import sys
>>> sys.path.insert(0, r'C:\Modules\Module1')
>>> import module

You shouldn't need to create the __init__.py file, not unless you're importing from within a package (so, if you were doing import package.module then you'd need __init__.py).

David Zaslavsky
+1  A: 

inserting in sys.path (at the very first place) works better:

>>> import sys
>>> sys.path.insert(0, 'C:/Modules/Module1')
>>> import module
>>> del sys.path[0]  # if you don't want that directory in the path

append to a list puts the item in the last place, so it's quite possible that other previous entries in the path take precedence; putting the directory in the first place is therefore a sounder approach.

Alex Martelli