dynamically generating a module
Steven D. Majewski
sdm7g at Virginia.EDU
Tue Nov 13 18:23:44 EST 2001
On 13 Nov 2001, Hung Jung Lu wrote:
> Here is one more challenge: is it possible to create a module on the
> fly?
>
> Suppose I have the ASCII Python source code of a module-to-be, or even
> better, suppose that I have the compiled byte code of a module-to-be,
> stored in a Python string. Is there a simple way (meaning not tweaking
> at C++ level) of making the module-to-be into a real module, without
> hitting the harddrive?
Sure: all you have to do is create an empty module and exec the code
in that modules namespace:
import new
codestr = open( source_file ).read() ## source code in codestr
module1 = new.module( 'module1' ) ## create a new, empty module
exec codestr in module1.__dict__ ## exec code in module namespace
dir( module1 ) ## inspect contents
## or, with a compiled module
module2 = new.module( 'module2' )
code = compile( codestr, 'none', 'exec' ) ## 'none' can be anyname
exec code in module2.__dict__
-- Steve
More information about the Python-list
mailing list