Exemplo n.º 1
0
ScriptResult PythonEngine::runPythonScript(const QString &script, const QString &fileName)
{
    m_isRunning = true;
    m_stdOut = "";

    QSettings settings;
    // enable user module deleter
    if (settings.value("PythonEngine/UserModuleDeleter", true).toBool())
        deleteUserModules();

    runPythonHeader();

    PyObject *output = NULL;
    if (QFile::exists(fileName))
    {
        QString str = QString("from os import chdir; chdir(u'" + QFileInfo(fileName).absolutePath() + "')");
        PyRun_String(str.toStdString().c_str(), Py_single_input, m_dict, m_dict);
    }
    // compile
    PyObject *code = Py_CompileString(script.toStdString().c_str(), fileName.toStdString().c_str(), Py_file_input);
    // run
    if (code) output = PyEval_EvalCode((PyCodeObject *) code, m_dict, m_dict);

    ScriptResult scriptResult;
    if (output)
    {
        scriptResult.isError = false;
        scriptResult.text = m_stdOut.trimmed();
    }
    else
    {
        scriptResult = parseError();
    }
    Py_XDECREF(output);

    m_isRunning = false;

    emit executedScript();

    return scriptResult;
}
Exemplo n.º 2
0
bool PythonEngine::runScript(const QString &script, const QString &fileName, bool useProfiler)
{
    m_isScriptRunning = true;

    PyGILState_STATE gstate = PyGILState_Ensure();

    emit startedScript();

    bool successfulRun = false;

    QSettings settings;
    // enable user module deleter
    if (settings.value("PythonEngine/UserModuleDeleter", true).toBool())
        deleteUserModules();

    runPythonHeader();

    PyObject *output = NULL;
    if (QFile::exists(fileName))
    {
        QString str = QString("from os import chdir; chdir(u'" + QFileInfo(fileName).absolutePath() + "')");
#pragma omp critical(import)
        {
            PyObject *import = PyRun_String(str.toLatin1().data(), Py_single_input, m_dict, m_dict);
            Py_XDECREF(import);
        }
    }

    // compile
    PyObject *code = Py_CompileString(script.toLatin1().data(), fileName.toLatin1().data(), Py_file_input);
    // run
    if (useProfiler)
    {
        setProfilerFileName(fileName);
        startProfiler();
    }
    if (code) output = PyEval_EvalCode((PyCodeObject *) code, m_dict, m_dict);
    if (useProfiler)
        finishProfiler();

    if (output)
    {
        successfulRun = true;
        Py_XDECREF(output);
    }
    else
    {
        // error traceback
        Py_XDECREF(errorType);
        Py_XDECREF(errorValue);
        Py_XDECREF(errorTraceback);
        PyErr_Fetch(&errorType, &errorValue, &errorTraceback);
        if (errorTraceback)
            successfulRun = false;
    }

    Py_XDECREF(code);

    m_isScriptRunning = false;

    // release the thread, no Python API allowed beyond this point
    PyGILState_Release(gstate);

    emit executedScript();

    return successfulRun;
}