diff --git a/include/boost/python/exec.hpp b/include/boost/python/exec.hpp index 903b29d4..359830a4 100644 --- a/include/boost/python/exec.hpp +++ b/include/boost/python/exec.hpp @@ -13,18 +13,25 @@ namespace boost namespace python { +// Evaluate python expression from str. +// global and local are the global and local scopes respectively, +// used during evaluation. +object +BOOST_PYTHON_DECL +eval(str string, object global = object(), object local = object()); + // Execute python source code from str. // global and local are the global and local scopes respectively, // used during execution. object -BOOST_PYTHON_DECL +BOOST_PYTHON_DECL exec(str string, object global = object(), object local = object()); // Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object -BOOST_PYTHON_DECL +BOOST_PYTHON_DECL exec_file(str filename, object global = object(), object local = object()); } diff --git a/src/exec.cpp b/src/exec.cpp index 5f2b8bc6..050cc63e 100644 --- a/src/exec.cpp +++ b/src/exec.cpp @@ -13,6 +13,15 @@ namespace boost namespace python { +object BOOST_PYTHON_DECL eval(str string, object global, object local) +{ + // should be 'char const *' but older python versions don't use 'const' yet. + char *s = python::extract(string); + PyObject* result = PyRun_String(s, Py_eval_input, global.ptr(), local.ptr()); + if (!result) throw_error_already_set(); + return object(detail::new_reference(result)); +} + object BOOST_PYTHON_DECL exec(str string, object global, object local) { // should be 'char const *' but older python versions don't use 'const' yet. diff --git a/test/exec.cpp b/test/exec.cpp index 1843d183..bad33c6f 100644 --- a/test/exec.cpp +++ b/test/exec.cpp @@ -49,6 +49,13 @@ BOOST_PYTHON_MODULE(embedded_hello) } +void eval_test() +{ + python::object result = python::eval("'abcdefg'.upper()"); + std::string value = python::extract(result) BOOST_EXTRACT_WORKAROUND; + BOOST_TEST(value == "ABCDEFG"); +} + void exec_test() { // Register the module with the interpreter @@ -108,7 +115,8 @@ int main(int argc, char **argv) // Initialize the interpreter Py_Initialize(); - if (python::handle_exception(exec_test) || + if (python::handle_exception(eval_test) || + python::handle_exception(exec_test) || python::handle_exception(boost::bind(exec_file_test, script))) { if (PyErr_Occurred())