能从ObjC调用Python模块吗?

8 投票
2 回答
3484 浏览
提问于 2025-04-15 11:15

使用PyObjC,是否可以导入一个Python模块,调用一个函数,并将结果以NSString的形式返回?

比如,做一些类似于下面的Python代码的事情:

import mymodule
result = mymodule.mymethod()

..用伪ObjC表示:

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

2 个回答

3

不太一样,按照我所知道的,你可以用“C语言的方式”来做,就像在这个链接中提到的 http://lists.apple.com/archives/Cocoa-dev/2004/Jan/msg00598.html,或者用“Pyobjc的方式”,可以参考这个链接 http://osdir.com/ml/python.pyobjc.devel/2005-06/msg00019.html(你也可以查看这个讨论串里的其他信息,以获得更多的解释)。

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

另外,这个教程也不错

撰写回答