Skip to content

Instantly share code, notes, and snippets.

@gogo40
Created October 13, 2015 16:39
Show Gist options
  • Save gogo40/d307a9e1b9b9034403f6 to your computer and use it in GitHub Desktop.
Save gogo40/d307a9e1b9b9034403f6 to your computer and use it in GitHub Desktop.
//=================================
GsTLAppli_Python_initialize::GsTLAppli_Python_initialize()
{
Py_InitializeEx(1);
PyEval_InitThreads();
}
GsTLAppli_Python_initialize::~GsTLAppli_Python_initialize()
{
Py_Finalize();
}
void GsTLAppli_Python_redirect_output()
{
PyRun_SimpleString(""
"import redirect\n"
"class CoutLogger:\n"
" def __init__(self):\n"
" self.buf = []\n"
" def write(self, data):\n"
" self.buf.append(data)\n"
" if data.endswith('\\n'):\n"
" redirect.sgems_cout(''.join(self.buf))\n"
" self.buf = []\n"
"\n"
"class CerrLogger:\n"
" def __init__(self):\n"
" self.buf = []\n"
" def write(self, data):\n"
" self.buf.append(data)\n"
" if data.endswith('\\n'):\n"
" redirect.sgems_cerr(''.join(self.buf))\n"
" self.buf = []\n"
"\n"
"import sys\n"
"sys.stdout = CoutLogger()\n"
"sys.stderr = CerrLogger()\n"
"");
}
std::atomic<int> g_python_running_threads;
PyThreadState* g_thread_state = 0;
GsTLAppli_Python_ensure_gil_state::GsTLAppli_Python_ensure_gil_state()
{
if (g_python_running_threads > 0) {
_state = PyGILState_Ensure();
_is_slave_thread = true;
} else {
if (g_thread_state != 0) {
PyEval_RestoreThread(g_thread_state);
g_thread_state = 0;
}
_is_slave_thread = false;
}
++g_python_running_threads;
}
GsTLAppli_Python_ensure_gil_state::~GsTLAppli_Python_ensure_gil_state()
{
if (_is_slave_thread) {
PyGILState_Release(_state);
} else {
g_thread_state = PyEval_SaveThread();
}
--g_python_running_threads;
}
void GsTLAppli_Python_init()
{
g_python_running_threads = 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment