[Cython] Direct log output to sys.stdout

This fixes the problem of some output (notably from the 1D solver)
going to std::cout when that is not the primary output location,
e.g. when using IDLE or the IPython QtConsole.
This commit is contained in:
Ray Speth 2013-12-06 23:15:14 +00:00
parent 3f92b77f5a
commit ff842a1a08
3 changed files with 28 additions and 0 deletions

View file

@ -1,7 +1,10 @@
#include "cantera/base/logger.h"
#include "cantera/thermo/ThermoPhase.h"
#include "cantera/transport/TransportBase.h"
#include "cantera/kinetics/Kinetics.h"
#include "Python.h"
// Wrappers for preprocessor defines
std::string get_cantera_version()
{
@ -13,6 +16,23 @@ int get_sundials_version()
return SUNDIALS_VERSION;
}
class PythonLogger : public Cantera::Logger
{
public:
virtual void write(const std::string& s) {
// 1000 bytes is the maximum size permitted by PySys_WriteStdout
static const size_t N = 999;
for (size_t i = 0; i < s.size(); i+=N) {
PySys_WriteStdout("%s", s.substr(i, N).c_str());
}
}
virtual void error(const std::string& msg) {
std::string err = "raise Exception('''"+msg+"''')";
PyRun_SimpleString(err.c_str());
}
};
// Function which populates a 1D array
#define ARRAY_FUNC(PREFIX, CLASS_NAME, FUNC_NAME) \
void PREFIX ## _ ## FUNC_NAME(Cantera::CLASS_NAME* object, double* data) \

View file

@ -505,6 +505,11 @@ cdef extern from "cantera/cython/wrappers.h":
cdef string get_cantera_version()
cdef int get_sundials_version()
cdef cppclass CxxPythonLogger "PythonLogger":
pass
cdef void CxxSetLogger "setLogger" (CxxPythonLogger*)
# ThermoPhase composition
cdef void thermo_getMassFractions(CxxThermoPhase*, double*) except +
cdef void thermo_setMassFractions(CxxThermoPhase*, double*) except +

View file

@ -1,6 +1,9 @@
import sys
cdef int _pythonMajorVersion = sys.version_info[0]
cdef CxxPythonLogger* _logger = new CxxPythonLogger()
CxxSetLogger(_logger)
cdef string stringify(x):
""" Converts Python strings to std::string. """
# This method works with both Python 2.x and 3.x.