Exemple #1
0
bool Python::load()
{
    InputOutput::ScreenManager *S = InputOutput::ScreenManager::singleton();
    char msg[1024];
    PyObject *modName;

    char comm[512];
    strcpy(comm, "");
    PyRun_SimpleString("curdir = os.getcwd()");
    const char *path = getFolderFromFilePath((const char*)_script);
    const char *filename = getFileNameFromFilePath((const char*)_script);
    if(path[0]=='.')   // "./" prefix has been set
        sprintf(comm, "modulePath = curdir + \"%s\"", &path[1]);
    else
        sprintf(comm, "modulePath = \"%s\"", path);
    PyRun_SimpleString(comm);
    PyRun_SimpleString("sys.path.append(modulePath)");

    modName = PyUnicode_FromString(filename);
    _module = PyImport_Import(modName);
    Py_DECREF(modName); modName=0;
    if(!_module){
        sprintf(msg,
                "Python module \"%s\" cannot be imported.\n",
                filename);
        S->addMessageF(3, msg);
        printf("\n--- Python report --------------------------\n\n");
        PyErr_Print();
        printf("\n-------------------------- Python report ---\n");
        return true;
    }

    _func = PyObject_GetAttrString(_module, "main");
    if(!_func || !PyCallable_Check(_func)) {
        S->addMessageF(3, "main() function cannot be found.\n");
        printf("\n--- Python report --------------------------\n\n");
        PyErr_Print();
        printf("\n-------------------------- Python report ---\n");
        return true;
    }
    return false;
}
Exemple #2
0
void Python::load()
{
    PyObject *modName;

    std::ostringstream comm;
    PyRun_SimpleString("curdir = os.getcwd()");
    std::string path = trimCopy(getFolderFromFilePath(_script));
    std::string filename = trimCopy(getFileNameFromFilePath(_script));
    if(path.at(0) == '.')   // "./" prefix has been set
        comm << "modulePath = curdir + \"" << path.substr(1) << "\"";
    else
        comm << "modulePath = \"" << path << "\"";
    PyRun_SimpleString(comm.str().c_str());
    PyRun_SimpleString("sys.path.append(modulePath)");

    modName = PyUnicode_FromString(filename.c_str());
    _module = PyImport_Import(modName);
    Py_DECREF(modName); modName=0;
    if(!_module){
        std::ostringstream msg;
        msg << "Python module \"" << filename
            << "\" cannot be imported." << std::endl;
        LOG(L_ERROR, msg.str());
        printf("\n--- Python report --------------------------\n\n");
        PyErr_Print();
        printf("\n-------------------------- Python report ---\n");
        throw std::runtime_error("Python execution error");
    }

    _func = PyObject_GetAttrString(_module, "main");
    if(!_func || !PyCallable_Check(_func)) {
        LOG(L_ERROR, "main() function cannot be found.\n");
        printf("\n--- Python report --------------------------\n\n");
        PyErr_Print();
        printf("\n-------------------------- Python report ---\n");
        throw std::runtime_error("Python execution error");
    }
}