Directly importing a .pyc file?
effbot at telia.com
Wed Sep 6 23:15:21 CEST 2000
Richard Harvey wrote:
> I've successfully figured out how to parse, compile, and import in a module
> through the C API, using the following pseudocode:
> node = PyParser_SimpleParseFile(f, moduleName, 256);
> code = PyNode_Compile(node, moduleName);
> module = PyImport_ImportModule(moduleName);
you only need the last line...
> At the point PyImport_ImportModule is called, Python writes out the .pyc
> file for my script. My question is this: if I detect that a .pyc file
> exists, is there a way to directly import it without repeating the compile
> step? I want to know this to determine if I can successfully distribute
> precompiled scripts without requiring the original .py file.
your compile step doesn't do what you think: it creates a code
object in memory, but doesn't create a module (same thing as
"compile" on the Python level -- you don't need to call "compile"
before you can use "import").
the easiest way to do what you want is to use the PyImport_Import
function, which works exactly as Python's import statement:
module = PyImport_Import(moduleName);
this locates the module source file, compiles it if necessary, and
creates the module. if the source file cannot be found, it loads
the module from the corresponding PYC file.
see section 6.1.2 in the tutorial for more information:
<!-- daily news from the python universe:
More information about the Python-list