-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.cpp
51 lines (38 loc) · 1.24 KB
/
run.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "run.hpp"
#include <boost/python.hpp>
#include "throw.hpp"
#include "Error.hpp"
namespace pccl {
namespace python {
namespace {
boost::python::object makeNamespace()
{
Py_InitializeEx(false/*signals*/);
using namespace boost::python;
object mainModule(handle<>(borrowed(PyImport_AddModule("__main__"))));
object mainNamespace = mainModule.attr("__dict__");
return mainNamespace;
}
boost::python::object const& runFile(boost::python::object const& mainNamespace, char const* filename)
try
{
FILE *file = fopen(filename, "r");
pccl_unless(file, pccl_throw_errno("failed to open file: ", filename));
// capture the result of PyRun_* so it is cleaned up later
boost::python::handle<>(PyRun_FileEx(file, filename, Py_file_input,
mainNamespace.ptr(), mainNamespace.ptr(),
true/*close*/));
return mainNamespace;
}
catch (boost::python::error_already_set const &)
{
BOOST_THROW_EXCEPTION(python::Error());
}
} // namespace
boost::python::object runFile(char const* filename)
{
boost::python::object mainNamespace = makeNamespace();
return runFile(mainNamespace, filename);
}
} // namespace python
} // namespace pccl