1 | // Copyright Stefan Seefeld 2005. |
---|
2 | // Distributed under the Boost Software License, Version 1.0. (See |
---|
3 | // accompanying file LICENSE_1_0.txt or copy at |
---|
4 | // http://www.boost.org/LICENSE_1_0.txt) |
---|
5 | |
---|
6 | #include <boost/python/exec.hpp> |
---|
7 | #include <boost/python/borrowed.hpp> |
---|
8 | #include <boost/python/extract.hpp> |
---|
9 | #include <boost/python/handle.hpp> |
---|
10 | |
---|
11 | namespace boost |
---|
12 | { |
---|
13 | namespace python |
---|
14 | { |
---|
15 | |
---|
16 | object BOOST_PYTHON_DECL eval(str string, object global, object local) |
---|
17 | { |
---|
18 | // should be 'char const *' but older python versions don't use 'const' yet. |
---|
19 | char *s = python::extract<char *>(string); |
---|
20 | PyObject* result = PyRun_String(s, Py_eval_input, global.ptr(), local.ptr()); |
---|
21 | if (!result) throw_error_already_set(); |
---|
22 | return object(detail::new_reference(result)); |
---|
23 | } |
---|
24 | |
---|
25 | object BOOST_PYTHON_DECL exec(str string, object global, object local) |
---|
26 | { |
---|
27 | // should be 'char const *' but older python versions don't use 'const' yet. |
---|
28 | char *s = python::extract<char *>(string); |
---|
29 | PyObject* result = PyRun_String(s, Py_file_input, global.ptr(), local.ptr()); |
---|
30 | if (!result) throw_error_already_set(); |
---|
31 | return object(detail::new_reference(result)); |
---|
32 | } |
---|
33 | |
---|
34 | // Execute python source code from file filename. |
---|
35 | // global and local are the global and local scopes respectively, |
---|
36 | // used during execution. |
---|
37 | object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) |
---|
38 | { |
---|
39 | // should be 'char const *' but older python versions don't use 'const' yet. |
---|
40 | char *f = python::extract<char *>(filename); |
---|
41 | // Let python open the file to avoid potential binary incompatibilities. |
---|
42 | PyObject *pyfile = PyFile_FromString(f, "r"); |
---|
43 | if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); |
---|
44 | python::handle<> file(pyfile); |
---|
45 | PyObject* result = PyRun_File(PyFile_AsFile(file.get()), |
---|
46 | f, |
---|
47 | Py_file_input, |
---|
48 | global.ptr(), local.ptr()); |
---|
49 | if (!result) throw_error_already_set(); |
---|
50 | return object(detail::new_reference(result)); |
---|
51 | } |
---|
52 | |
---|
53 | } // namespace boost::python |
---|
54 | } // namespace boost |
---|