是否可以从 ObjC 调用 Python 模块? [英] Is it possible to call a Python module from ObjC?
问题描述
使用 PyObjC,是否可以导入 Python 模块、调用函数并以(例如)NSString 形式获取结果?
Using PyObjC, is it possible to import a Python module, call a function and get the result as (say) a NSString?
例如,执行以下 Python 代码的等效操作:
For example, doing the equivalent of the following Python code:
import mymodule
result = mymodule.mymethod()
..在伪ObjC中:
PyModule *mypymod = [PyImport module:@"mymodule"];
NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"];
推荐答案
如 Alex Martelli 的回答中所述(尽管邮件列表消息中的链接已损坏,但它应该是 https://docs.python.org/extending/embedding.html#pure-embedding).. C 方式打电话..
As mentioned in Alex Martelli's answer (although the link in the mailing-list message was broken, it should be https://docs.python.org/extending/embedding.html#pure-embedding).. The C way of calling..
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
) - Add the Python.framework to your project (Right click
External Frameworks..
,Add > Existing Frameworks
. The framework in in/System/Library/Frameworks/
- Add
/System/Library/Frameworks/Python.framework/Headers
to your "Header Search Path" (Project > Edit Project Settings
)
下面的代码应该可以工作(虽然它可能不是有史以来最好的代码......)
The following code should work (although it's probably not the best code ever written..)
#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];
}
还有本教程很好
这篇关于是否可以从 ObjC 调用 Python 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!