| 100 | } |
| 101 | |
| 102 | bool PythonScript::execute(ScriptAPIInterface * tw) const |
| 103 | { |
| 104 | // Load the script |
| 105 | QFile scriptFile(m_Filename); |
| 106 | if (!scriptFile.open(QIODevice::ReadOnly)) { |
| 107 | // handle error |
| 108 | return false; |
| 109 | } |
| 110 | QString contents = m_Codec->toUnicode(scriptFile.readAll()); |
| 111 | scriptFile.close(); |
| 112 | |
| 113 | // Python seems to require Unix style line endings |
| 114 | if (contents.contains("\r")) |
| 115 | contents.replace(QRegularExpression("\r\n?"), "\n"); |
| 116 | |
| 117 | // Remember the current thread state so we can restore it at the end |
| 118 | PyThreadState* origThreadState = PyThreadState_Get(); |
| 119 | |
| 120 | // Create a separate sub-interpreter for this script |
| 121 | PyThreadState* interpreter = Py_NewInterpreter(); |
| 122 | |
| 123 | // Register the types |
| 124 | if (!registerPythonTypes(tw->GetResult())) { |
| 125 | Py_EndInterpreter(interpreter); |
| 126 | // Restore the original thread state |
| 127 | PyThreadState_Swap(origThreadState); |
| 128 | return false; |
| 129 | } |
| 130 | |
| 131 | pyQObject * TW = (pyQObject*)QObjectToPython(tw->self()); |
| 132 | if (!TW) { |
| 133 | tw->SetResult(tr("Could not create TW")); |
| 134 | Py_EndInterpreter(interpreter); |
| 135 | // Restore the original thread state |
| 136 | PyThreadState_Swap(origThreadState); |
| 137 | return false; |
| 138 | } |
| 139 | |
| 140 | // Run the script |
| 141 | PyObject * globals = PyDict_New(); |
| 142 | PyObject * locals = PyDict_New(); |
| 143 | |
| 144 | // Create a dictionary of global variables |
| 145 | // without the __builtins__ module, nothing would work! |
| 146 | PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()); |
| 147 | PyDict_SetItemString(globals, "TW", _PyObject_CAST(TW)); |
| 148 | |
| 149 | PyObject * ret = nullptr; |
| 150 | |
| 151 | if (globals && locals) |
| 152 | ret = PyRun_String(qPrintable(contents), Py_file_input, globals, locals); |
| 153 | |
| 154 | Py_XDECREF(globals); |
| 155 | Py_XDECREF(locals); |
| 156 | Py_XDECREF(ret); |
| 157 | Py_XDECREF(TW); |
| 158 | |
| 159 | // Check for exceptions |