Skip to content

Commit dffdc3f

Browse files
author
Roberto De Ioris
committed
added ue.exec(filename) to run python scripts from the console
1 parent 9fb6160 commit dffdc3f

3 files changed

Lines changed: 31 additions & 0 deletions

File tree

‎Source/UnrealEnginePython/Private/UEPyModule.cpp‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,17 @@ static PyObject *py_unreal_engine_py_gc(PyObject * self, PyObject * args) {
7272

7373
}
7474

75+
static PyObject *py_unreal_engine_exec(PyObject * self, PyObject * args) {
76+
char *filename = nullptr;
77+
if (!PyArg_ParseTuple(args, "s:exec", &filename)) {
78+
return NULL;
79+
}
80+
FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython");
81+
PythonModule.RunFile(filename);
82+
Py_INCREF(Py_None);
83+
return Py_None;
84+
}
85+
7586
static PyMethodDef unreal_engine_methods[] = {
7687
{ "log", py_unreal_engine_log, METH_VARARGS, "" },
7788
{ "log_warning", py_unreal_engine_log_warning, METH_VARARGS, "" },
@@ -128,6 +139,7 @@ static PyMethodDef unreal_engine_methods[] = {
128139
{ "add_ticker", py_unreal_engine_add_ticker, METH_VARARGS, "" },
129140

130141
{ "py_gc", py_unreal_engine_py_gc, METH_VARARGS, "" },
142+
{ "exec", py_unreal_engine_exec, METH_VARARGS, "" },
131143

132144
{ NULL, NULL },
133145
};

‎Source/UnrealEnginePython/Private/UnrealEnginePython.cpp‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,24 @@ void FUnrealEnginePythonModule::RunString(char *str) {
103103
Py_DECREF(eval_ret);
104104
}
105105

106+
void FUnrealEnginePythonModule::RunFile(char *filename) {
107+
FScopePythonGIL gil;
108+
char *full_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts"), *FString("/"), UTF8_TO_TCHAR(filename)));
109+
FILE *fd = nullptr;
110+
111+
if (fopen_s(&fd, full_path, "r") != 0) {
112+
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
113+
return;
114+
}
115+
PyObject *eval_ret = PyRun_File(fd, full_path, Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
116+
fclose(fd);
117+
if (!eval_ret) {
118+
unreal_engine_py_log_error();
119+
return;
120+
}
121+
Py_DECREF(eval_ret);
122+
}
123+
106124
#undef LOCTEXT_NAMESPACE
107125

108126
IMPLEMENT_MODULE(FUnrealEnginePythonModule, UnrealEnginePython)

‎Source/UnrealEnginePython/Public/UnrealEnginePython.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class UNREALENGINEPYTHON_API FUnrealEnginePythonModule : public IModuleInterface
1818
virtual void ShutdownModule() override;
1919

2020
void RunString(char *);
21+
void RunFile(char *);
2122

2223
private:
2324
void *ue_python_gil;

0 commit comments

Comments
 (0)