55
66#include < boost/python/exec.hpp>
77#include < boost/python/borrowed.hpp>
8+ #include < boost/python/dict.hpp>
89#include < boost/python/extract.hpp>
910#include < boost/python/handle.hpp>
1011
@@ -15,6 +16,15 @@ namespace python
1516
1617object BOOST_PYTHON_DECL eval (str string, object global, object local)
1718{
19+ // Set suitable default values for global and local dicts.
20+ if (!global)
21+ {
22+ if (PyObject *g = PyEval_GetGlobals ())
23+ global = object (detail::borrowed_reference (g));
24+ else
25+ global = dict ();
26+ }
27+ if (!local) local = global;
1828 // should be 'char const *' but older python versions don't use 'const' yet.
1929 char *s = python::extract<char *>(string);
2030 PyObject* result = PyRun_String (s, Py_eval_input, global.ptr (), local.ptr ());
@@ -24,18 +34,54 @@ object BOOST_PYTHON_DECL eval(str string, object global, object local)
2434
2535object BOOST_PYTHON_DECL exec (str string, object global, object local)
2636{
37+ // Set suitable default values for global and local dicts.
38+ if (!global)
39+ {
40+ if (PyObject *g = PyEval_GetGlobals ())
41+ global = object (detail::borrowed_reference (g));
42+ else
43+ global = dict ();
44+ }
45+ if (!local) local = global;
2746 // should be 'char const *' but older python versions don't use 'const' yet.
2847 char *s = python::extract<char *>(string);
2948 PyObject* result = PyRun_String (s, Py_file_input, global.ptr (), local.ptr ());
3049 if (!result) throw_error_already_set ();
3150 return object (detail::new_reference (result));
3251}
3352
53+ object BOOST_PYTHON_DECL exec_statement (str string, object global, object local)
54+ {
55+ // Set suitable default values for global and local dicts.
56+ if (!global)
57+ {
58+ if (PyObject *g = PyEval_GetGlobals ())
59+ global = object (detail::borrowed_reference (g));
60+ else
61+ global = dict ();
62+ }
63+ if (!local) local = global;
64+ // should be 'char const *' but older python versions don't use 'const' yet.
65+ char *s = python::extract<char *>(string);
66+ PyObject* result = PyRun_String (s, Py_single_input, global.ptr (), local.ptr ());
67+ if (!result) throw_error_already_set ();
68+ return object (detail::new_reference (result));
69+ }
70+
3471// Execute python source code from file filename.
3572// global and local are the global and local scopes respectively,
3673// used during execution.
3774object BOOST_PYTHON_DECL exec_file (str filename, object global, object local)
3875{
76+ // Set suitable default values for global and local dicts.
77+ if (!global)
78+ {
79+ if (PyObject *g = PyEval_GetGlobals ())
80+ global = object (detail::borrowed_reference (g));
81+ else
82+ global = dict ();
83+ }
84+ if (!local) local = global;
3985 // should be 'char const *' but older python versions don't use 'const' yet.
4086 char *f = python::extract<char *>(filename);
4187 // Let python open the file to avoid potential binary incompatibilities.
0 commit comments