/
PythonConsoleWriter.h
51 lines (42 loc) · 1001 Bytes
/
PythonConsoleWriter.h
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
#pragma once
#include "itextstream.h"
#include <pybind11/pybind11.h>
namespace py = pybind11;
namespace script
{
/**
* greebo: A small helper class for redirecting Python's StdIo output
* to DarkRadiant's global*() streams.
*
* The output is duplicated to a given string.
*/
class PythonConsoleWriter
{
private:
// whether to write to output or error stream
bool _isErrorLogger;
// A buffer keeping the messages until read
std::string& _outputBuffer;
public:
PythonConsoleWriter(bool isErrorLogger, std::string& outputBuffer) :
_isErrorLogger(isErrorLogger),
_outputBuffer(outputBuffer)
{}
// StdOut redirector
void write(const std::string& msg)
{
_outputBuffer.append(msg);
// Python doesn't send entire lines, it may send single characters,
// so don't add std::endl each time
if (_isErrorLogger)
{
rError() << msg;
}
else
{
rMessage() << msg;
}
}
};
typedef py::class_<PythonConsoleWriter> PythonConsoleWriterClass;
} // namespace script