-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathPythonScript.cpp
More file actions
79 lines (72 loc) · 1.78 KB
/
Copy pathPythonScript.cpp
File metadata and controls
79 lines (72 loc) · 1.78 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <osg/Version>
#include <iostream>
#include "PythonScript.h"
using namespace osgVerse;
extern void pythonWrapperOsg();
#ifdef WITH_PYTHON
# include <Python.h>
# include "pybind11/pybind11.h"
# include "pybind11/embed.h"
struct PythonObject : public osg::Referenced
{
std::map<std::string, pybind11::module_> modules;
pybind11::scoped_interpreter guard;
PythonObject()
{
try
{
modules["osg"] = pybind11::module_::import("osg");
// TODO
}
catch (std::exception& e)
{
OSG_WARN << "[PythonScript] Failed importing modules: "
<< e.what() << std::endl;
}
}
};
#else
struct PythonObject : public osg::Referenced
{
std::map<std::string, std::string> modules;
};
#endif
PythonScript::PythonScript(const wchar_t* pythonPath)
{
#if defined(WITH_PYTHON) && !defined(VERSE_WASM)
if (pythonPath != NULL) Py_SetPythonHome(pythonPath);
#endif
try
{
pythonWrapperOsg();
_pythonObject = new PythonObject;
}
catch (const std::exception& e)
{
OSG_WARN << "[PythonScript] Initialization error: " << e.what() << std::endl;
}
}
PythonScript::~PythonScript()
{
PythonObject* pobj = static_cast<PythonObject*>(_pythonObject.get());
if (pobj) pobj->modules.clear(); // clear modules first
}
bool PythonScript::execute(const std::string& code)
{
#ifdef WITH_PYTHON
try
{
pybind11::exec(code);
// pybind11::eval_file("script.py");
}
catch (const pybind11::error_already_set& e)
{
OSG_WARN << "[PythonScript] Execution error: " << e.what() << std::endl;
return false;
}
return true;
#else
OSG_WARN << "[PythonScript] Not implemented" << std::endl;
return false;
#endif
}