Exemplo n.º 1
0
PyObject* PythonSecurity::compile_restricted(const QString& source, const QString& filename, const QString& mode)
{
    krossdebug("PythonSecurity::compile_restricted");
    if(! m_pymodule)
        initRestrictedPython(); // throws exception if failed

    try {
        Py::Dict mainmoduledict = ((PythonInterpreter*)m_interpreter)->mainModule()->getDict();

        PyObject* func = PyDict_GetItemString(m_pymodule->getDict().ptr(), "compile_restricted");
        if(! func)
            throw Kross::Api::Exception::Ptr( new Kross::Api::Exception(QString("No such function '%1'.").arg("compile_restricted")) );

        Py::Callable funcobject(func, true); // the funcobject takes care of freeing our func pyobject.

        if(! funcobject.isCallable())
            throw Kross::Api::Exception::Ptr( new Kross::Api::Exception(QString("Function '%1' is not callable.").arg("compile_restricted")) );

        Py::Tuple args(3);
        args[0] = Py::String(source.utf8());
        args[1] = Py::String(filename.utf8());
        args[2] = Py::String(mode.utf8());

        Py::Object result = funcobject.apply(args);

        PyObject* pycode = PyEval_EvalCode(
            (PyCodeObject*)result.ptr(),
            mainmoduledict.ptr(),
            mainmoduledict.ptr()
        );
        if(! pycode)
            throw Py::Exception();

        /*
        Py::List ml = mainmoduledict;
        for(Py::List::size_type mi = 0; mi < ml.length(); ++mi) {
            krossdebug( QString("dir() = %1").arg( ml[mi].str().as_string().c_str() ) );
            //krossdebug( QString("dir().dir() = %1").arg( Py::Object(ml[mi]).dir().as_string().c_str() ) );
        }
        */

        Py::Object code(pycode);
        krossdebug( QString("%1 callable=%2").arg(code.as_string().c_str()).arg(PyCallable_Check(code.ptr())) );
        Py::List l = code.dir();
        for(Py::List::size_type i = 0; i < l.length(); ++i) {
            krossdebug( QString("dir() = %1").arg( l[i].str().as_string().c_str() ) );
            //krossdebug( QString("dir().dir() = %1").arg( Py::Object(l[i]).dir().as_string().c_str() ) );
        }

        return pycode;
    }
    catch(Py::Exception& e) { 
        QString err = Py::value(e).as_string().c_str();
        e.clear();
        throw Kross::Api::Exception::Ptr( new Kross::Api::Exception(QString("Function '%1' failed with python exception: %2").arg("compile_restricted").arg(err) ) );
    }
}
Exemplo n.º 2
0
void TooltablePy::setTools(Py::Dict arg)
{
    getTooltablePtr()->Tools.clear();
    PyObject* dict_copy = PyDict_Copy(arg.ptr());
    PyObject *key, *value;
    Py_ssize_t pos = 0;
    while (PyDict_Next(dict_copy, &pos, &key, &value)) {
        if ( PyObject_TypeCheck(key,&(PyInt_Type)) && (PyObject_TypeCheck(value,&(Path::ToolPy::Type))) ) {
            int ckey = (int)PyInt_AsLong(key);
            Path::Tool &tool = *static_cast<Path::ToolPy*>(value)->getToolPtr();
            getTooltablePtr()->setTool(tool,ckey);
        } else {
            throw Py::Exception("The dictionary can only contain int:tool pairs");
        }
    }
}
Exemplo n.º 3
0
void PythonSecurity::initRestrictedPython()
{
    try {
        Py::Dict mainmoduledict = ((PythonInterpreter*)m_interpreter)->mainModule()->getDict();
        PyObject* pymodule = PyImport_ImportModuleEx(
            "RestrictedPython", // name of the module being imported (may be a dotted name)
            mainmoduledict.ptr(), // reference to the current global namespace
            mainmoduledict.ptr(), // reference to the local namespace
            0 // PyObject *fromlist
        );
        if(! pymodule)
            throw Py::Exception();
        m_pymodule = new Py::Module(pymodule, true);

        PyObject* pyrun = PyRun_String(
            //"import os\n"
            //"import sys\n"
            "import __main__\n"
            "import PythonSecurity\n"
            "from RestrictedPython import compile_restricted, PrintCollector\n"
            "from RestrictedPython.Eval import RestrictionCapableEval\n"
            "from RestrictedPython.RCompile import RModule\n"

            "setattr(__main__, '_getattr_', PythonSecurity._getattr_)\n"
            "setattr(__main__, '_print_', PrintCollector)\n"
            ,
            Py_file_input,
            m_pymodule->getDict().ptr(),
            m_pymodule->getDict().ptr()
        );
        if(! pyrun)
            throw Py::Exception();

        krossdebug("PythonSecurity::PythonSecurity SUCCESSFULLY LOADED");
    }
    catch(Py::Exception& e) {
        QString err = Py::value(e).as_string().c_str();
        e.clear();
        throw Kross::Api::Exception::Ptr( new Kross::Api::Exception(QString("Failed to initialize PythonSecurity module: %1").arg(err) ) );
    }
}
Exemplo n.º 4
0
    Py::Object projectToSVG(const Py::Tuple& args, const Py::Dict& keys)
        {
            static char* argNames[] = {"topoShape", "direction", "type", "tolerance", "vStyle", "v0Style", "v1Style", "hStyle", "h0Style", "h1Style", NULL};
            PyObject *pcObjShape = 0;
            PyObject *pcObjDir = 0;
            const char *extractionTypePy = 0;
            ProjectionAlgos::ExtractionType extractionType = ProjectionAlgos::Plain;
            const float tol = 0.1f;
            PyObject* vStylePy = 0;
            ProjectionAlgos::XmlAttributes vStyle;
            PyObject* v0StylePy = 0;
            ProjectionAlgos::XmlAttributes v0Style;
            PyObject* v1StylePy = 0;
            ProjectionAlgos::XmlAttributes v1Style;
            PyObject* hStylePy = 0;
            ProjectionAlgos::XmlAttributes hStyle;
            PyObject* h0StylePy = 0;
            ProjectionAlgos::XmlAttributes h0Style;
            PyObject* h1StylePy = 0;
            ProjectionAlgos::XmlAttributes h1Style;
        
            // Get the arguments

            if (!PyArg_ParseTupleAndKeywords(
                    args.ptr(), keys.ptr(), 
                    "O!|O!sfOOOOOO", 
                    argNames,
                    &(TopoShapePy::Type), &pcObjShape,
                    &(Base::VectorPy::Type), &pcObjDir, 
                    &extractionTypePy, &tol, 
                    &vStylePy, &v0StylePy, &v1StylePy, 
                    &hStylePy, &h0StylePy, &h1StylePy))
          
                throw Py::Exception();

            // Convert all arguments into the right format

            TopoShapePy* pShape = static_cast<TopoShapePy*>(pcObjShape);

            Base::Vector3d directionVector(0,0,1);
            if (pcObjDir)
                directionVector = static_cast<Base::VectorPy*>(pcObjDir)->value();

            if (extractionTypePy && string(extractionTypePy) == "ShowHiddenLines")
                extractionType = ProjectionAlgos::WithHidden;

            if (vStylePy)
                copy(Py::Dict(vStylePy), inserter(vStyle, vStyle.begin()));
            if (v0StylePy)
                copy(Py::Dict(v0StylePy), inserter(v0Style, v0Style.begin()));
            if (v1StylePy)
                copy(Py::Dict(v1StylePy), inserter(v1Style, v1Style.begin()));
            if (hStylePy)
                copy(Py::Dict(hStylePy), inserter(hStyle, hStyle.begin()));
            if (h0StylePy)
                copy(Py::Dict(h0StylePy), inserter(h0Style, h0Style.begin()));
            if (h1StylePy)
                copy(Py::Dict(h1StylePy), inserter(h1Style, h1Style.begin()));
        
            // Execute the SVG generation

            ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(), 
                                directionVector);
            Py::String result(Alg.getSVG(extractionType, tol, 
                                         vStyle, v0Style, v1Style, 
                                         hStyle, h0Style, h1Style));
            return result;
        }
Exemplo n.º 5
0
QMap<QString, CallTip> CallTipsList::extractTips(const QString& context) const
{
    Base::PyGILStateLocker lock;
    QMap<QString, CallTip> tips;
    if (context.isEmpty())
        return tips;

    try {
        Py::Module module("__main__");
        Py::Dict dict = module.getDict();
#if 0
        QStringList items = context.split(QLatin1Char('.'));
        QString modname = items.front();
        items.pop_front();
        if (!dict.hasKey(std::string(modname.toLatin1())))
            return tips; // unknown object

        // get the Python object we need
        Py::Object obj = dict.getItem(std::string(modname.toLatin1()));
        while (!items.isEmpty()) {
            QByteArray name = items.front().toLatin1();
            std::string attr = name.constData();
            items.pop_front();
            if (obj.hasAttr(attr))
                obj = obj.getAttr(attr);
            else
                return tips;
        }
#else
        // Don't use hasattr & getattr because if a property is bound to a method this will be executed twice.
        PyObject* code = Py_CompileString(static_cast<const char*>(context.toLatin1()), "<CallTipsList>", Py_eval_input);
        if (!code) {
            PyErr_Clear();
            return tips;
        }

        PyObject* eval = 0;
        if (PyCode_Check(code)) {
            eval = PyEval_EvalCode(reinterpret_cast<PyCodeObject*>(code), dict.ptr(), dict.ptr());
        }
        Py_DECREF(code);
        if (!eval) {
            PyErr_Clear();
            return tips;
        }
        Py::Object obj(eval, true);
#endif

        // Checks whether the type is a subclass of PyObjectBase because to get the doc string
        // of a member we must get it by its type instead of its instance otherwise we get the
        // wrong string, namely that of the type of the member. 
        // Note: 3rd party libraries may use their own type object classes so that we cannot 
        // reliably use Py::Type. To be on the safe side we should use Py::Object to assign
        // the used type object to.
        //Py::Object type = obj.type();
        Py::Object type(PyObject_Type(obj.ptr()), true);
        Py::Object inst = obj; // the object instance 
        union PyType_Object typeobj = {&Base::PyObjectBase::Type};
        union PyType_Object typedoc = {&App::DocumentObjectPy::Type};
        union PyType_Object basetype = {&PyBaseObject_Type};

        if (PyObject_IsSubclass(type.ptr(), typedoc.o) == 1) {
            // From the template Python object we don't query its type object because there we keep
            // a list of additional methods that we won't see otherwise. But to get the correct doc
            // strings we query the type's dict in the class itself.
            // To see if we have a template Python object we check for the existence of supportedProperties
            if (!type.hasAttr("supportedProperties")) {
                obj = type;
            }
        }
        else if (PyObject_IsSubclass(type.ptr(), typeobj.o) == 1) {
            obj = type;
        }
        else if (PyInstance_Check(obj.ptr())) {
            // instances of old style classes
            PyInstanceObject* inst = reinterpret_cast<PyInstanceObject*>(obj.ptr());
            PyObject* classobj = reinterpret_cast<PyObject*>(inst->in_class);
            obj = Py::Object(classobj);
        }
        else if (PyObject_IsInstance(obj.ptr(), basetype.o) == 1) {
            // New style class which can be a module, type, list, tuple, int, float, ...
            // Make sure it's not a type objec
            union PyType_Object typetype = {&PyType_Type};
            if (PyObject_IsInstance(obj.ptr(), typetype.o) != 1) {
                // this should be now a user-defined Python class
                // http://stackoverflow.com/questions/12233103/in-python-at-runtime-determine-if-an-object-is-a-class-old-and-new-type-instan
                if (Py_TYPE(obj.ptr())->tp_flags & Py_TPFLAGS_HEAPTYPE) {
                    obj = type;
                }
            }
        }

        // If we have an instance of PyObjectBase then determine whether it's valid or not
        if (PyObject_IsInstance(inst.ptr(), typeobj.o) == 1) {
            Base::PyObjectBase* baseobj = static_cast<Base::PyObjectBase*>(inst.ptr());
            const_cast<CallTipsList*>(this)->validObject = baseobj->isValid();
        }
        else {
            // PyObject_IsInstance might set an exception
            PyErr_Clear();
        }

        Py::List list(obj.dir());

        // If we derive from PropertyContainerPy we can search for the properties in the
        // C++ twin class.
        union PyType_Object proptypeobj = {&App::PropertyContainerPy::Type};
        if (PyObject_IsSubclass(type.ptr(), proptypeobj.o) == 1) {
            // These are the attributes of the instance itself which are NOT accessible by
            // its type object
            extractTipsFromProperties(inst, tips);
        }

        // If we derive from App::DocumentPy we have direct access to the objects by their internal
        // names. So, we add these names to the list, too.
        union PyType_Object appdoctypeobj = {&App::DocumentPy::Type};
        if (PyObject_IsSubclass(type.ptr(), appdoctypeobj.o) == 1) {
            App::DocumentPy* docpy = (App::DocumentPy*)(inst.ptr());
            App::Document* document = docpy->getDocumentPtr();
            // Make sure that the C++ object is alive
            if (document) {
                std::vector<App::DocumentObject*> objects = document->getObjects();
                Py::List list;
                for (std::vector<App::DocumentObject*>::iterator it = objects.begin(); it != objects.end(); ++it)
                    list.append(Py::String((*it)->getNameInDocument()));
                extractTipsFromObject(inst, list, tips);
            }
        }

        // If we derive from Gui::DocumentPy we have direct access to the objects by their internal
        // names. So, we add these names to the list, too.
        union PyType_Object guidoctypeobj = {&Gui::DocumentPy::Type};
        if (PyObject_IsSubclass(type.ptr(), guidoctypeobj.o) == 1) {
            Gui::DocumentPy* docpy = (Gui::DocumentPy*)(inst.ptr());
            if (docpy->getDocumentPtr()) {
                App::Document* document = docpy->getDocumentPtr()->getDocument();
                // Make sure that the C++ object is alive
                if (document) {
                    std::vector<App::DocumentObject*> objects = document->getObjects();
                    Py::List list;
                    for (std::vector<App::DocumentObject*>::iterator it = objects.begin(); it != objects.end(); ++it)
                        list.append(Py::String((*it)->getNameInDocument()));
                    extractTipsFromObject(inst, list, tips);
                }
            }
        }

        // These are the attributes from the type object
        extractTipsFromObject(obj, list, tips);
    }
    catch (Py::Exception& e) {
        // Just clear the Python exception
        e.clear();
    }

    return tips;
}
Exemplo n.º 6
0
    Py::Object approxSurface(const Py::Tuple& args, const Py::Dict& kwds)
    {
        PyObject *o;
        // spline parameters
        int uDegree = 3;
        int vDegree = 3;
        int uPoles = 6;
        int vPoles = 6;
        // smoothing
        PyObject* smooth = Py_True;
        double weight = 0.1;
        double grad = 1.0;  //0.5
        double bend = 0.0; //0.2
        // other parameters
        int iteration = 5;
        PyObject* correction = Py_True;
        double factor = 1.0;

        static char* kwds_approx[] = {"Points", "UDegree", "VDegree", "NbUPoles", "NbVPoles",
                                      "Smooth", "Weight", "Grad", "Bend",
                                      "Iterations", "Correction", "PatchFactor", NULL};
        if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O|iiiiO!dddiO!d",kwds_approx,
                                        &o,&uDegree,&vDegree,&uPoles,&vPoles,
                                        &PyBool_Type,&smooth,&weight,&grad,&bend,
                                        &iteration,&PyBool_Type,&correction,&factor))
            throw Py::Exception();

        double curvdiv = 1.0 - (grad + bend);
        int uOrder = uDegree + 1;
        int vOrder = vDegree + 1;

        // error checking
        if (grad < 0.0 || grad > 1.0) {
            throw Py::ValueError("Value of Grad out of range [0,1]");
        }
        if (bend < 0.0 || bend > 1.0) {
            throw Py::ValueError("Value of Bend out of range [0,1]");
        }
        if (curvdiv < 0.0 || curvdiv > 1.0) {
            throw Py::ValueError("Sum of Grad and Bend out of range [0,1]");
        }
        if (uDegree < 1 || uOrder > uPoles) {
            throw Py::ValueError("Value of uDegree out of range [1,NbUPoles-1]");
        }
        if (vDegree < 1 || vOrder > vPoles) {
            throw Py::ValueError("Value of vDegree out of range [1,NbVPoles-1]");
        }

        try {
            Py::Sequence l(o);
            TColgp_Array1OfPnt clPoints(0, l.size()-1);
            if (clPoints.Length() < uPoles * vPoles) {
                throw Py::ValueError("Too less data points for the specified number of poles");
            }

            int index=0;
            for (Py::Sequence::iterator it = l.begin(); it != l.end(); ++it) {
                Py::Tuple t(*it);
                clPoints(index++) = gp_Pnt(
                    (double)Py::Float(t.getItem(0)),
                    (double)Py::Float(t.getItem(1)),
                    (double)Py::Float(t.getItem(2)));
            }

            Reen::BSplineParameterCorrection pc(uOrder,vOrder,uPoles,vPoles);
            Handle_Geom_BSplineSurface hSurf;

            pc.EnableSmoothing(PyObject_IsTrue(smooth) ? true : false, weight, grad, bend, curvdiv);
            hSurf = pc.CreateSurface(clPoints, iteration, PyObject_IsTrue(correction) ? true : false, factor);
            if (!hSurf.IsNull()) {
                return Py::asObject(new Part::BSplineSurfacePy(new Part::GeomBSplineSurface(hSurf)));
            }

            throw Py::RuntimeError("Computation of B-Spline surface failed");
        }
        catch (Standard_Failure &e) {
            std::string str;
            Standard_CString msg = e.GetMessageString();
            str += typeid(e).name();
            str += " ";
            if (msg) {str += msg;}
            else     {str += "No OCCT Exception Message";}
            throw Py::RuntimeError(str);
        }
        catch (const Base::Exception &e) {
            throw Py::RuntimeError(e.what());
        }
        catch (...) {
            throw Py::RuntimeError("Unknown C++ exception");
        }
    }
Exemplo n.º 7
0
    Py::Object meshFromShape(const Py::Tuple& args, const Py::Dict& kwds)
    {
        PyObject *shape;

        static char* kwds_maxLength[] = {"Shape", "MaxLength",NULL};
        PyErr_Clear();
        double maxLength=0;
        if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!d", kwds_maxLength,
                                        &(Part::TopoShapePy::Type), &shape, &maxLength)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setMaxLength(maxLength);
            mesher.setRegular(true);
            return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
        }

        static char* kwds_maxArea[] = {"Shape", "MaxArea",NULL};
        PyErr_Clear();
        double maxArea=0;
        if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!d", kwds_maxArea,
                                        &(Part::TopoShapePy::Type), &shape, &maxArea)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setMaxArea(maxArea);
            mesher.setRegular(true);
            return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
        }

        static char* kwds_localLen[] = {"Shape", "LocalLength",NULL};
        PyErr_Clear();
        double localLen=0;
        if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!d", kwds_localLen,
                                        &(Part::TopoShapePy::Type), &shape, &localLen)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setLocalLength(localLen);
            mesher.setRegular(true);
            return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
        }

        static char* kwds_deflection[] = {"Shape", "Deflection",NULL};
        PyErr_Clear();
        double deflection=0;
        if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!d", kwds_deflection,
                                        &(Part::TopoShapePy::Type), &shape, &deflection)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setDeflection(deflection);
            mesher.setRegular(true);
            return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
        }

        static char* kwds_minmaxLen[] = {"Shape", "MinLength","MaxLength",NULL};
        PyErr_Clear();
        double minLen=0, maxLen=0;
        if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!dd", kwds_minmaxLen,
                                        &(Part::TopoShapePy::Type), &shape, &minLen, &maxLen)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setMinMaxLengths(minLen, maxLen);
            mesher.setRegular(true);
            return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
        }

#if defined (HAVE_NETGEN)
        static char* kwds_fineness[] = {"Shape", "Fineness", "SecondOrder", "Optimize", "AllowQuad",NULL};
        PyErr_Clear();
        int fineness=0, secondOrder=0, optimize=1, allowquad=0;
        if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!i|iii", kwds_fineness,
                                        &(Part::TopoShapePy::Type), &shape, &fineness,
                                        &secondOrder, &optimize, &allowquad)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
            mesher.setMethod(MeshPart::Mesher::Netgen);
            mesher.setFineness(fineness);
            mesher.setSecondOrder(secondOrder > 0);
            mesher.setOptimize(optimize > 0);
            mesher.setQuadAllowed(allowquad > 0);
            return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
        }

        static char* kwds_user[] = {"Shape", "GrowthRate", "SegPerEdge", "SegPerRadius", "SecondOrder", "Optimize", "AllowQuad",NULL};
        PyErr_Clear();
        double growthRate=0, nbSegPerEdge=0, nbSegPerRadius=0;
        if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!|dddiii", kwds_user,
                                        &(Part::TopoShapePy::Type), &shape,
                                        &growthRate, &nbSegPerEdge, &nbSegPerRadius,
                                        &secondOrder, &optimize, &allowquad)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
            mesher.setMethod(MeshPart::Mesher::Netgen);
            mesher.setGrowthRate(growthRate);
            mesher.setNbSegPerEdge(nbSegPerEdge);
            mesher.setNbSegPerRadius(nbSegPerRadius);
            mesher.setSecondOrder(secondOrder > 0);
            mesher.setOptimize(optimize > 0);
            mesher.setQuadAllowed(allowquad > 0);
            return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
        }
#endif

        PyErr_Clear();
        if (PyArg_ParseTuple(args.ptr(), "O!", &(Part::TopoShapePy::Type), &shape)) {
            MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
#if defined (HAVE_NETGEN)
            mesher.setMethod(MeshPart::Mesher::Netgen);
#else
            mesher.setMethod(MeshPart::Mesher::Mefisto);
            mesher.setRegular(true);
#endif
            return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
        }

        throw Py::Exception(Base::BaseExceptionFreeCADError,"Wrong arguments");
    }
Exemplo n.º 8
0
PythonInterpreter::PythonInterpreter(Kross::InterpreterInfo* info)
    : Kross::Interpreter(info)
    , d(new PythonInterpreterPrivate())
{
    // Initialize the python interpreter.
    initialize();

    // Set name of the program.
    Py_SetProgramName(const_cast<char*>("Kross"));

    /*
    // Set arguments.
    //char* comm[0];
    const char* comm = const_cast<char*>("kross"); // name.
    PySys_SetArgv(1, comm);
    */

    // In the python sys.path are all module-directories are
    // listed in.
    QString path;

    // First import the sys-module to remember it's sys.path
    // list in our path QString.
    Py::Module sysmod( PyImport_ImportModule( (char*)"sys" ), true );
    Py::Dict sysmoddict = sysmod.getDict();
    Py::Object syspath = sysmoddict.getItem("path");
    if(syspath.isList()) {
        Py::List syspathlist = syspath;
        for(Py::List::iterator it = syspathlist.begin(); it != syspathlist.end(); ++it) {
            if( ! (*it).isString() ) continue;
            QString s = PythonType<QString>::toVariant(*it);
            path.append( s + PYPATHDELIMITER );
        }
    }
    else
        path = Py_GetPath();

#if 0
    // Determinate additional module-paths we like to add.
    // First add the global Kross modules-path.
    QStringList krossdirs = KGlobal::dirs()->findDirs("data", "kross/python");
    for(QStringList::Iterator krossit = krossdirs.begin(); krossit != krossdirs.end(); ++krossit)
        path.append(*krossit + PYPATHDELIMITER);
    // Then add the application modules-path.
    QStringList appdirs = KGlobal::dirs()->findDirs("appdata", "kross/python");
    for(QStringList::Iterator appit = appdirs.begin(); appit != appdirs.end(); ++appit)
        path.append(*appit + PYPATHDELIMITER);
#endif

    // Set the extended sys.path.
    PySys_SetPath( (char*) path.toLatin1().data() );

    #ifdef KROSS_PYTHON_INTERPRETER_DEBUG
        krossdebug(QString("Python ProgramName: %1").arg(Py_GetProgramName()));
        krossdebug(QString("Python ProgramFullPath: %1").arg(Py_GetProgramFullPath()));
        krossdebug(QString("Python Version: %1").arg(Py_GetVersion()));
        krossdebug(QString("Python Platform: %1").arg(Py_GetPlatform()));
        krossdebug(QString("Python Prefix: %1").arg(Py_GetPrefix()));
        krossdebug(QString("Python ExecPrefix: %1").arg(Py_GetExecPrefix()));
        //krossdebug(QString("Python Path: %1").arg(Py_GetPath()));
        //krossdebug(QString("Python System Path: %1").arg(path));
    #endif

    // Initialize the main module.
    d->mainmodule = new PythonModule(this);

    // The main dictonary.
    Py::Dict moduledict = d->mainmodule->getDict();
    //TODO moduledict["KrossPythonVersion"] = Py::Int(KROSS_PYTHON_VERSION);

    // Prepare the interpreter.
    QString s =
        //"# -*- coding: iso-8859-1 -*-\n"
        //"import locale\n"
        //"locale.setlocale(locale.LC_ALL, '')\n"
        //"# -*- coding: latin-1 -*\n"
        //"# -*- coding: utf-8 -*-\n"
        //"import locale\n"
        //"locale.setlocale(locale.LC_ALL, '')\n"
        //"from __future__ import absolute_import\n"
        "import sys\n"
        //"import os, os.path\n"
        //"sys.setdefaultencoding('latin-1')\n"

        // Dirty hack to get sys.argv defined. Needed for e.g. TKinter.
        "sys.argv = ['']\n"

        // On the try to read something from stdin always return an empty
        // string. That way such reads don't block our script.
        // Deactivated since sys.stdin has the encoding attribute needed
        // by e.g. LiquidWeather and those attr is missing in StringIO
        // and cause it's buildin we can't just add it but would need to
        // implement our own class. Grrrr, what a stupid design :-/
        //"try:\n"
        //"    import cStringIO\n"
        //"    sys.stdin = cStringIO.StringIO()\n"
        //"except:\n"
        //"    pass\n"

        // Class to redirect something. We use this class e.g. to redirect
        // <stdout> and <stderr> to a c++ event.
        //"class Redirect:\n"
        //"  def __init__(self, target):\n"
        //"    self.target = target\n"
        //"  def write(self, s):\n"
        //"    self.target.call(s)\n"

        // Wrap builtin __import__ method. All import requests are
        // first redirected to our PythonModule.import method and
        // if the call returns None, then we call the original
        // python import mechanism.
        "import __builtin__\n"
        "import __main__\n"
        "import traceback\n"
        "sys.modules['_oldmain'] = sys.modules['__main__']\n"
        "_main_builtin_import_ = __main__.__builtin__.__import__\n"
        "class _Importer:\n"
        "   def __init__(self, script):\n"
        "       self.script = script\n"
        "       self.realImporter = __main__.__builtin__.__import__\n"
        "       __main__.__builtin__.__import__ = self._import\n"
        "   def _import(self, name, globals=None, locals=None, fromlist=[], level = -1):\n"
        //"       try:\n"
        //"           print \"1===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n"
#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 5)
        "           mod = __main__._import(self.script, name, globals, locals, fromlist, level)\n"
#else
        "           mod = __main__._import(self.script, name, globals, locals, fromlist)\n"
#endif
        "           if mod == None:\n"
        "               if name == 'qt':\n"
        "                   raise ImportError('Import of the PyQt3 module is not allowed. Please use PyQt4 instead.')\n"
        "               if name == 'dcop':\n"
        "                   raise ImportError('Import of the KDE3 DCOP module is not allowed. Please use PyQt4 DBUS instead.')\n"
#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 5)
        "               mod = self.realImporter(name, globals, locals, fromlist, level)\n"
#else
        "               mod = self.realImporter(name, globals, locals, fromlist)\n"
#endif
        "           if mod != None:\n"
        //"               print \"3===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n"
        "               if globals != None and (not fromlist or len(fromlist)==0 or '*' in fromlist):\n"
        "                   globals[name] = mod\n"
        "           return mod\n"
        //"       except ImportError:\n"
        //"       except:\n"
        //"           print \"9===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
        //"           print \" \".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )\n"
        //"       return None\n"

/*
        "       print \"_Importer name=%s fromlist=%s\" % (name,fromlist)\n"
        "       if fromlist == None:\n"
        "           mod = __main__._import(self.script, name, globals, locals, fromlist)\n"
        "           if mod != None:\n"
        "               print \"2===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n"
        "               globals[name] = mod\n"
        "               return mod\n"
        //"           if name in sys.modules:\n" // hack to preserve module paths, needed e.g. for "import os.path"
        //"               print \"3===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n"
        //"               return sys.modules[name]\n"
        "       print \"3===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
        "       try:\n"
        "           mod = self.realImporter(name, globals, locals, fromlist)\n"
        "           print \"4===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s module=%s\" % (name,fromlist,name in sys.modules,mod)\n"
        //"           mod.__init__(name)\n"
        //"           globals[name] = mod\n"
        //"           sys.modules[name] = mod\n"
        "           print \"5===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s module=%s\" % (name,fromlist,name in sys.modules,mod)\n"
        "           return mod\n"
        "       except ImportError:\n"
        "           print \"6===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
        "           n = name.split('.')\n"
        "           if len(n) >= 2:\n"
        "               print \"7===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
        "               m = self._import(\".\".join(n[:-1]),globals,locals,[n[-1],])\n"
        "               print \"8===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
        "               return self.realImporter(name, globals, locals, fromlist)\n"
        "           print \"9===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
        "           raise\n"
*/
        ;

    PyObject* pyrun = PyRun_String(s.toLatin1().data(), Py_file_input, moduledict.ptr(), moduledict.ptr());
    if(! pyrun) {
        Py::Object errobj = Py::value(Py::Exception()); // get last error
        setError( QString("Failed to prepare the __main__ module: %1").arg(errobj.as_string().c_str()) );
    }
    Py_XDECREF(pyrun); // free the reference.
}