1864
Comment: Python docs for imp module
|
← Revision 3 as of 2008-11-15 14:00:40 ⇥
1866
converted to 1.6 markup
|
Deletions are marked like this. | Additions are marked like this. |
Line 65: | Line 65: |
* [http://docs.python.org/lib/module-imp.html Python documentation for imp module] | * [[http://docs.python.org/lib/module-imp.html|Python documentation for imp module]] |
The imp module lets you load a module at run-time, knowing just the name of the module.
Playing with imp Module
Make a file "eraseme.py":
1 print "Successfully imported!"
Then, at the python shell,
The find_module line searches for "eraseme" in the current working directory (".").
The first two returned items are self-explanatory, but what about that tuple- ('.py', 'U', 1) ..?
The first (".py") is obviously the extension.
'U' means, "I opened the file in UniversalNewline mode." Basically, universal newline mode is like read ("r"), except that it interprets all newline forms the same way.
Finally, the 1 is a code that matches against imp.PY_SOURCE (1), imp.PY_COMPILED (2), or imp.C_EXTENSION (3). Basically, it's telling us that the .py file is a source file.
Once you have this stuff, it's easy to load:
Note that, you don't have to play by the rules. If you wanted to, you could have said:
...even though the file's real name is "eggs.py".
See Also
Discussion
- (none yet!)