You can use eval(text), but this will bring code and not exactly a module.
Be careful since brython is not mature (Pierre is re-writing part of it),
you could face some issues like:
a = """
print('hello world')
"""
eval(a)
working fine, but not:
a = """
print("hello world")
"""
eval(a)
(notice the quotes change in print)
You could also have a look at import code:
http://code.google.com/p/brython/source/browse/trunk/py_import.jsmore precisely at function '$import_py()' the code starting at 'var stack = $py2js(res,module)'
just seems to require the data (res) and a module name (module) to perform the task.
A new import mechanism could be hooked by just creating a $import_xxx() method
and adding it to the list of importers ( $import_funcs = [$import_js,$import_py,$import_xxx].
This new method will have to retrieve the text of the module from a module name.
Again be aware that issues are reported on importing, and the same issues for eval() may apply.
Here is a simple example illustring the topic:
<html>
<head>
<title>Brython test string import</title>
<script src="brython.js"></script>
<meta charset="utf-8"/>
</head>
<script>
function import_from_string(res, module){
var stack = $py2js(res,module)
// insert module name as a JS object
stack.list.splice(0,0,['code',module+'= new object()'],['newline','\n'])
// search for module-level names
// functions
var $pos=0
while(true){
var $mlname_pos = stack.find_next_at_same_level($pos,"keyword","function")
if($mlname_pos===null){break}
var $func_name = stack.list[$mlname_pos+1][1]
stack.list.splice($mlname_pos,2,['code',module+'.'+$func_name+"=function"])
// modify declaration at the end of function
var br_pos = stack.find_next($mlname_pos,'bracket','{')
var br_end = stack.find_next_matching(br_pos)
var $fend = stack.find_next(br_end,"func_end")
var $fend_code = stack.list[$fend][1]
$fend_code = module+'.'+$fend_code.substr(1)
$pv_pos = $fend_code.search(';')
$fend_code = ";"+$fend_code.substr(0,$pv_pos)
stack.list[$fend][1] = $fend_code
$pos = $mlname_pos+1
}
// variables
var $pos=0
while(true){
var $mlname_pos = stack.find_next_at_same_level($pos,"assign_id")
if($mlname_pos===null){break}
stack.list[$mlname_pos][1]=module+'.'+stack.list[$mlname_pos][1]
$pos = $mlname_pos+1
}
try{
eval(stack.to_js())
// add class and __str__
eval(module+'.__class__ = $type')
eval(module+'.__str__ = function(){return "<module \''+module+"'>\"}")
}catch(err){
$raise(
err.name,err.message)
}
}
</script>
<body onLoad="brython(1)">
<script type="text/python">
some_code = """
def hello(n, text):
for i in range(n):
doc <= P(str(i) + ' Hello ' + text)
"""
import_from_string(some_code, "my_module")
my_module.hello(10, "world")
</script>
</body>
</html>
Pedro