Ja, diesen Weg beschreite ich jetzt.
Also schlanke extra Klasse, die möglichst nur den Python-Header verwendet.
So geht es erstmal.
Schick, Python zu embedden
Nur ein als Datei vorliegendes Skript bekomme ich noch nicht gerufen.
Falls das jemand mal braucht:
Aufruf/ Benutzen des Python-Interpreters von C++/ Qt aus:
Code: Alles auswählen
// Attention! The #include of Python.h does not work,
// if one includes <QtCore> and many other Qt header before this include.
#include "python3.2m/Python.h"
#include <QDebug>
#include <QList>
#include <QString>
int executeSimpleString();
int executeSimpleStringAndGetResult();
int main() {
executeSimpleStringAndGetResult();
// executeSimpleString();
}
//---------------------------------------------------------------------------------------------------------------------
int executeSimpleStringAndGetResult() {
Py_Initialize();
QString s = "import math\n";
s.append( "result = math.sin( 0.5 * math.pi )\n" );
s.append( "print( type( result ) )\n" );
const char* charS = s.toAscii().data();
PyRun_SimpleStringFlags( charS, 0 );
PyObject * module = PyImport_AddModule( "__main__" );
if ( module > 0 ) {
PyObject * dictionary = PyModule_GetDict( module );
if ( dictionary > 0 ) {
PyObject * result = PyDict_GetItemString( dictionary, "result" );
if ( result > 0 ) {
double res = PyFloat_AsDouble( result );
qDebug() << res;
}
}
}
Py_Finalize();
return 0;
}
//---------------------------------------------------------------------------------------------------------------------
int executeSimpleString() {
Py_Initialize();
QString s = "import math\n";
s.append( "for x in range(1, 11):\n" );
s.append( " res = math.pow( x, 2 )\n" );
s.append( " print( 'x = ' + str( x ) + ' res = ' + str( res ) )\n" );
const char* charS = s.toAscii().data();
PyRun_SimpleStringFlags( charS, 0 );
Py_Finalize();
return 0;
}
Das Qt-Projektfile benötigt folgenden Eintrag (natürlich angepasst):
Code: Alles auswählen
INCLUDEPATH += $$quote(/home/JR/Development/lib/Cpp/Python-3.2.2/include)
LIBS += -L$$quote($$/home/JR/Development/lib/Cpp/Python-3.2.2/lib) -lpython3.2m
Und beim Ausführen des Executables (z.B. namens "PythonEmbedding") muss die Umgebungsvariable LD_LIBRARY_PATH den Verzeichnispfad zum Directory lib enthalten.
Im vorliegenden Beispiel also folgendes Shellskript zum Starten der Mini-App:
Code: Alles auswählen
export LD_LIBRARY_PATH=/home/JR/Development/lib/Cpp/Python-3.2.2/lib
./PythonEmbedding
Viele Grüße
JR
P.S.: Hilfreich ist folgender Link zur C/C++ API von Python:
http://docs.python.org/py3k/genindex.html