diff --git a/src/exec.cpp b/src/exec.cpp index 6c30797a..5dfe033b 100644 --- a/src/exec.cpp +++ b/src/exec.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include @@ -15,6 +16,15 @@ namespace python object BOOST_PYTHON_DECL eval(str string, object global, object local) { + // Set suitable default values for global and local dicts. + if (!global) + { + if (PyObject *g = PyEval_GetGlobals()) + global = object(detail::borrowed_reference(g)); + else + global = dict(); + } + if (!local) local = global; // 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()); @@ -24,6 +34,15 @@ object BOOST_PYTHON_DECL eval(str string, object global, object local) object BOOST_PYTHON_DECL exec(str string, object global, object local) { + // Set suitable default values for global and local dicts. + if (!global) + { + if (PyObject *g = PyEval_GetGlobals()) + global = object(detail::borrowed_reference(g)); + else + global = dict(); + } + if (!local) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *s = python::extract(string); PyObject* result = PyRun_String(s, Py_file_input, global.ptr(), local.ptr()); @@ -31,11 +50,38 @@ object BOOST_PYTHON_DECL exec(str string, object global, object local) return object(detail::new_reference(result)); } +object BOOST_PYTHON_DECL exec_statement(str string, object global, object local) +{ + // Set suitable default values for global and local dicts. + if (!global) + { + if (PyObject *g = PyEval_GetGlobals()) + global = object(detail::borrowed_reference(g)); + else + global = dict(); + } + if (!local) local = global; + // should be 'char const *' but older python versions don't use 'const' yet. + char *s = python::extract(string); + PyObject* result = PyRun_String(s, Py_single_input, global.ptr(), local.ptr()); + if (!result) throw_error_already_set(); + return object(detail::new_reference(result)); +} + // Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { + // Set suitable default values for global and local dicts. + if (!global) + { + if (PyObject *g = PyEval_GetGlobals()) + global = object(detail::borrowed_reference(g)); + else + global = dict(); + } + if (!local) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract(filename); // Let python open the file to avoid potential binary incompatibilities.