Ist es möglich, ein Python-Modul von ObjC anrufen?
-
16-09-2019 - |
Frage
Mit PyObjC ist es möglich, ein Python-Modul zu importieren, eine Funktion aufrufen und das Ergebnis als (sagen wir) ein NSString bekommen?
Zum Beispiel macht das Äquivalent des folgenden Python-Code:
import mymodule
result = mymodule.mymethod()
.. in pseudo-ObjC:
PyModule *mypymod = [PyImport module:@"mymodule"];
NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"];
Lösung
Wie in Alex Martelli Antwort erwähnt (obwohl der Link in der Mailing-Liste Nachricht gebrochen wurde, soll es sein https://docs.python.org/extending/embedding.html#pure-embedding ) .. Die C Art des Aufrufs ..
print urllib.urlopen("http://google.com").read()
- Fügen Sie den Python.framework zu einem Projekt (Rechtsklick
External Frameworks..
,Add > Existing Frameworks
. Der Rahmen in in/System/Library/Frameworks/
- Fügen Sie
/System/Library/Frameworks/Python.framework/Headers
zu Ihrem "Header-Suchpfad" (Project > Edit Project Settings
)
Der folgende Code funktionieren soll (obwohl es wahrscheinlich nicht der beste Code jemals geschrieben ..)
#include <Python.h>
int main(){
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Py_Initialize();
// import urllib
PyObject *mymodule = PyImport_Import(PyString_FromString("urllib"));
// thefunc = urllib.urlopen
PyObject *thefunc = PyObject_GetAttrString(mymodule, "urlopen");
// if callable(thefunc):
if(thefunc && PyCallable_Check(thefunc)){
// theargs = ()
PyObject *theargs = PyTuple_New(1);
// theargs[0] = "http://google.com"
PyTuple_SetItem(theargs, 0, PyString_FromString("http://google.com"));
// f = thefunc.__call__(*theargs)
PyObject *f = PyObject_CallObject(thefunc, theargs);
// read = f.read
PyObject *read = PyObject_GetAttrString(f, "read");
// result = read.__call__()
PyObject *result = PyObject_CallObject(read, NULL);
if(result != NULL){
// print result
printf("Result of call: %s", PyString_AsString(result));
}
}
[pool release];
}
Auch dieses Tutorial ist gut
Andere Tipps
Nicht ganz, AFAIK, aber Sie können es tun "um die C Art und Weise", wie zum Beispiel in http://lists.apple.com/archives/Cocoa-dev/2004/Jan/msg00598.html - oder "der PyObjC Weg", wie er per http://osdir.com/ml/python.pyobjc.devel/2005 -06 / msg00019.html (siehe auch alle anderen Nachrichten auf diesem Thread zur weiteren Klärung).