15 #ifdef BORNAGAIN_PYTHON
27 #if PY_MAJOR_VERSION >= 3
28 PyObject* pyStr = PyUnicode_AsEncodedString(obj,
"utf-8",
"Error ~");
29 result = std::string(PyBytes_AsString(pyStr));
32 result = std::string(PyString_AsString(obj));
40 std::vector<std::string> result;
42 if (PyTuple_Check(obj)) {
43 for (Py_ssize_t i = 0; i < PyTuple_Size(obj); i++) {
44 PyObject* value = PyTuple_GetItem(obj, i);
48 }
else if (PyList_Check(obj)) {
49 for (Py_ssize_t i = 0; i < PyList_Size(obj); i++) {
50 PyObject* value = PyList_GetItem(obj, i);
55 throw std::runtime_error(
"PyEmbeddedUtils::toVectorString() -> Error. Unexpected object.");
69 std::string PyEmbeddedUtils::toString(
wchar_t* c)
73 std::string result(wstr.begin(), wstr.end());
82 if (!Py_IsInitialized()) {
86 PyObject* sysPath = PySys_GetObject((
char*)
"path");
87 PyList_Append(sysPath, PyString_FromString(path.c_str()));
93 PyOS_sighandler_t sighandler;
94 sighandler = PyOS_getsig(SIGINT);
96 PyObject* pmod = PyImport_ImportModule(
"bornagain");
99 throw std::runtime_error(
"Can't load bornagain");
104 PyOS_setsig(SIGINT, sighandler);
113 std::stringstream result;
116 result << std::string(60,
'=') <<
"\n";
129 PyObject* sysPath = PySys_GetObject((
char*)
"path");
131 result <<
"sys.path: ";
132 for (
auto s : content)
144 std::stringstream result;
146 if (PyErr_Occurred()) {
147 PyObject *ptype, *pvalue, *ptraceback, *pystr;
149 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
150 pystr = PyObject_Str(pvalue);
151 if (
char* str = PyString_AsString(pystr))
152 result << std::string(str) <<
"\n";
154 PyObject* module_name = PyString_FromString(
"traceback");
155 PyObject* pyth_module = PyImport_Import(module_name);
156 Py_DecRef(module_name);
160 PyObject* pyth_func = PyObject_GetAttrString(pyth_module,
"format_exception");
161 if (pyth_func && PyCallable_Check(pyth_func)) {
163 PyObject_CallFunctionObjArgs(pyth_func, ptype, pvalue, ptraceback, NULL);
165 pystr = PyObject_Str(pyth_val);
166 if (
char* str = PyString_AsString(pystr))
167 result << std::string(str);
Defines PyEmbeddedUtils namespace.
std::string toString(PyObject *obj)
Converts PyObject into string, if possible, or throws exception.
std::vector< std::string > toVectorString(PyObject *obj)
Converts PyObject into vector of strings, if possible, or throws exception.
std::string pythonStackTrace()
Returns string representing python stack trace.
void import_bornagain(const std::string &path="")
Imports BornAgain from given location. If path is empty, tries to rely on PYTHONPATH.
std::string pythonRuntimeInfo()
Returns multi-line string representing PATH, PYTHONPATH, sys.path and other info.
Includes python header and takes care of warnings.
Defines various stuff in namespace Utils.
std::string getenv(const std::string &name)
Returns environment variable.