Skip to content

Commit dd9f0ca

Browse files
committed
Add support for the Python Stdout Log
You can use the print() and help() to display information
1 parent 9c77ab6 commit dd9f0ca

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

Source/UnrealEnginePython/Private/UnrealEnginePython.cpp

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,14 @@ void FUnrealEnginePythonModule::StartupModule()
9999

100100
UESetupPythonInterpeter(true);
101101

102-
PyObject *main_module = PyImport_AddModule("__main__");
103-
main_dict = PyModule_GetDict(main_module);
102+
main_module = PyImport_AddModule("__main__");
103+
main_dict = PyModule_GetDict((PyObject*)main_module);
104104
local_dict = main_dict;// PyDict_New();
105105

106+
// Redirecting stdout
107+
char const* code = "import sys\r\nclass StdoutCatcher :\r\n\tdef __init__(self) :\r\n\t\tself.data = ''\r\n\tdef flush(self) :\r\n\t\tself.data = ''\r\n\tdef write(self, stuff) :\r\n\t\tif(stuff.strip()!=''):\r\n\t\t\tself.data = self.data+'python: '+ stuff\r\ncatcher = StdoutCatcher()\r\nsys.stdout = catcher";
108+
PyRun_SimpleString(code);
109+
106110
if (PyImport_ImportModule("ue_site")) {
107111
UE_LOG(LogPython, Log, TEXT("ue_site Python module successfully imported"));
108112
}
@@ -139,6 +143,17 @@ void FUnrealEnginePythonModule::RunString(char *str) {
139143
if (!eval_ret) {
140144
unreal_engine_py_log_error();
141145
return;
146+
}else{
147+
//Get stdout output information
148+
PyObject* catcher = PyObject_GetAttrString((PyObject*)main_module, "catcher");
149+
PyObject* output = PyObject_GetAttrString(catcher, "data");
150+
char * buffer = PyString_AsString(output);
151+
UE_LOG(LogPython, Log, TEXT("%s"), ANSI_TO_TCHAR(buffer));
152+
153+
PyRun_SimpleString("sys.stdout.flush()");
154+
Py_DECREF(catcher);
155+
Py_DECREF(output);
156+
142157
}
143158
Py_DECREF(eval_ret);
144159
}

Source/UnrealEnginePython/Public/UnrealEnginePython.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class UNREALENGINEPYTHON_API FUnrealEnginePythonModule : public IModuleInterface
2626
// used by console
2727
void *main_dict;
2828
void *local_dict;
29+
void *main_module;
2930
};
3031

3132
struct FScopePythonGIL {

0 commit comments

Comments
 (0)