是否可以从ObjC调用Python模块?

时间:2009-04-26 01:52:07

标签: python objective-c pyobjc

使用PyObjC,是否可以导入Python模块,调用函数并将结果作为(比如说)NSString?

例如,执行以下Python代码的等效操作:

import mymodule
result = mymodule.mymethod()

..在伪ObjC中:

PyModule *mypymod = [PyImport module:@"mymodule"];
NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"];

2 个答案:

答案 0 :(得分:12)

正如Alex Martelli的回答中提到的那样(虽然邮件列表信息中的链接已被破坏,但应该是https://docs.python.org/extending/embedding.html#pure-embedding).. C方式呼叫..

print urllib.urlopen("http://google.com").read()
  • 将Python.framework添加到您的项目中(右键单击External Frameworks..Add > Existing Frameworks/System/Library/Frameworks/
  • 中的框架
  • /System/Library/Frameworks/Python.framework/Headers添加到“标题搜索路径”(Project > Edit Project Settings

以下代码应该可行(尽管它可能不是有史以来最好的代码..)

#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];
}

this tutorial也很好

答案 1 :(得分:3)

不完全是AFAIK,但是您可以按照http://lists.apple.com/archives/Cocoa-dev/2004/Jan/msg00598.html或“Pyobjc方式”的建议按照http://osdir.com/ml/python.pyobjc.devel/2005-06/msg00019.html进行“C方式”(另请参阅所有其他消息)在该主题上进一步澄清)。