[[SIGVerse with Python]]

We saw in the previous tutorial that the "exec" function runs the arbitrary code in the string parameter within the specified namespace. We showed the following examples for that, in which we showed the use of normal, non-imported code.

#highlight(python){{

py::exec("print 'Hello, world'", main_namespace);  
py::exec("print 'Hello, world'[3:5]", main_namespace);  
py::exec("print '.'.join(['1','2','3'])", main_namespace);  

}}


Of course, we would like to import modules (both user defined and pre-designed system modules) and extract values for them. 

Here, I will show one example of standard module "random". This tutorial is designed from taking some examples from the blog by [[Joseph Turner: http://thejosephturner.com/blog/page/1]]

#highlight(python){{

   boost::python::exec("import random", main_namespace);
   boost::python::object rand = boost::python::eval("random.random()",      main_namespace);
    std::cout << py::extract<double>(rand) << std::endl
}}

Here we imported the random module by executing the corresponding Python statement within the __main__ namespace, bringing the module into the namespace. After the module is available, we can use functions, objects, and variables within the namespace. In this example, we use the eval function, which returns the result of the passed-in Python statement, to create a boost::python object containing a random value as returned by the random() function in the random module. Finally, we extract the value as a C++ double type and print it.


As suggested in the blog by, [[Joseph Turner: http://thejosephturner.com/blog/page/1]], there is a more object oriented way to do this:

#highlight(python){{

    boost::python::object rand_mod = boost::python::import("random");
    boost::python::object rand_func = rand_mod.attr("random");
    boost::python::object rand2 = rand_func();
    std::cout << boost::python::extract(rand2) << std::endl;
}}


In this final example, we import the random module, but this time using the boost::python import function, which loads the module into a boost Python object. Next, the random function object is extracted from the random module and stored in a boost::python object. The function is called, returning a Python object containing the random number. Finally, the double value is extracted and printed. In general, all Python objects can be handled in this way – functions, classes, built-in types
















#highlight(end)

Front page   New List of pages Search Recent changes   Help   RSS of recent changes