29 template <eval_mode mode = eval_expr>
36 std::string
buffer =
"# -*- coding: utf-8 -*-\n" + (std::string) expr;
40 case eval_expr: start = Py_eval_input;
break;
43 default: pybind11_fail(
"invalid evaluation mode");
46 PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr());
49 return reinterpret_steal<object>(result);
52 template <eval_mode mode = eval_expr,
size_t N>
53 object eval(
const char (&s)[N],
object global =
globals(),
object local =
object()) {
55 auto expr = (s[0] ==
'\n') ?
str(module::import(
"textwrap").attr(
"dedent")(s))
57 return eval<mode>(expr, global, local);
60 inline void exec(
str expr,
object global =
globals(),
object local =
object()) {
61 eval<eval_statements>(expr, global, local);
65 void exec(
const char (&s)[N],
object global =
globals(),
object local =
object()) {
66 eval<eval_statements>(s, global, local);
69 template <eval_mode mode = eval_statements>
76 case eval_expr: start = Py_eval_input;
break;
79 default: pybind11_fail(
"invalid evaluation mode");
83 std::string fname_str = (std::string) fname;
84 #if PY_VERSION_HEX >= 0x03040000 85 FILE *f = _Py_fopen_obj(fname.
ptr(),
"r");
86 #elif PY_VERSION_HEX >= 0x03000000 87 FILE *f = _Py_fopen(fname.
ptr(),
"r");
90 auto fobj = reinterpret_steal<object>(PyFile_FromString(
91 const_cast<char *>(fname_str.c_str()),
92 const_cast<char*>(
"r")));
95 f = PyFile_AsFile(fobj.ptr());
100 pybind11_fail(
"File \"" + fname_str +
"\" could not be opened!");
103 #if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION) 104 PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(),
108 PyObject *result = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(),
109 local.ptr(), closeFile);
114 return reinterpret_steal<object>(result);
object eval(const char(&s)[N], object global=globals(), object local=object())
#define PYBIND11_NAMESPACE
PyObject * ptr() const
Return the underlying PyObject * pointer.
Evaluate a string containing a single statement. Returns none.
#define NAMESPACE_END(name)
object eval_file(str fname, object global=globals(), object local=object())
void exec(const char(&s)[N], object global=globals(), object local=object())
Evaluate a string containing a sequence of statement. Returns none.
Evaluate a string containing an isolated expression.
#define NAMESPACE_BEGIN(name)