bool PythonScripting::loadInitFile(const QString &path) { QFileInfo pyFile(path+".py"), pycFile(path+".pyc"); if (pycFile.isReadable() && (pycFile.lastModified() >= pyFile.lastModified())) return PyRun_SimpleFileEx(fopen(pycFile.filePath(), "rb"), pycFile.filePath(), true) == 0; else if (pyFile.isReadable()) { // try to compile pyFile to pycFile PyObject *compileModule = PyImport_ImportModule("py_compile"); if (compileModule) { PyObject *compile = PyDict_GetItemString(PyModule_GetDict(compileModule),"compile"); if (compile) { PyObject *tmp = PyObject_CallFunctionObjArgs(compile, PyString_FromString(pyFile.filePath()), PyString_FromString(pycFile.filePath()),NULL); if (tmp) Py_DECREF(tmp); else PyErr_Print(); } else PyErr_Print(); Py_DECREF(compileModule); } else PyErr_Print(); if (pycFile.isReadable() && (pycFile.lastModified() >= pyFile.lastModified())) { // run the newly compiled pycFile return PyRun_SimpleFileEx(fopen(pycFile.filePath(), "rb"), pycFile.filePath(), true) == 0; } else { // fallback: just run pyFile return PyRun_SimpleFileEx(fopen(pyFile.filePath(), "r"), pyFile.filePath(), true) == 0; } } return false; }
void Scripting::runFile(const QString &filename) { QFile pyFile(filename); pyFile.open(QIODevice::ReadOnly); QString s; QTextStream textStream(&pyFile); s.append(textStream.readAll()); pyFile.close(); evalScript(s, Py_file_input); }