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?

apalopohapa
  • 4,983
  • 5
  • 27
  • 29
  • See [How to import module from file name](http://stackoverflow.com/questions/67631/how-to-import-module-from-file-name) – Matthew Flaschen Jul 03 '10 at 23:53
  • Thanks for your responses. I do like the following approach: >>> import imp >>> m = imp.find_module('module',r'c:\modules\module1') >>> imp.load_module('module',m[0],m[1],m[2]) – apalopohapa Jul 04 '10 at 00:18
  • Possible duplicate of [How to import a module given the full path?](https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path) – wjandrea Nov 12 '18 at 02:30

2 Answers2

4

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 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).

Community
  • 1
  • 1
David Z
  • 128,184
  • 27
  • 255
  • 279
1

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
  • 854,459
  • 170
  • 1,222
  • 1,395