是否可以从ObjC调用Python模块?
问题描述:
使用PyObjC,有可能导入一个Python模块,调用一个函数并得到结果作为(比方说)一个NSString?是否可以从ObjC调用Python模块?
例如,执行以下Python代码相当于:
import mymodule
result = mymodule.mymethod()
..in伪ObjC:
PyModule *mypymod = [PyImport module:@"mymodule"];
NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"];
答
正如亚历马尔泰利的答案(虽然在邮件列表中的链接被打破,它应该是https://docs.python.org/extending/embedding.html#pure-embedding)提到..调用的C-方式..
print urllib.urlopen("http://google.com").read()
- 添加了Python。框架项目(权
/System/Library/Frameworks/
- 单击
External Frameworks..
,Add > Existing 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];
}
答
不完全是,据我所知,但你可以做到这一点的“THE C方式“,如http://lists.apple.com/archives/Cocoa-dev/2004/Jan/msg00598.html中所建议的那样 - 或按照http://osdir.com/ml/python.pyobjc.devel/2005-06/msg00019.html的”Pyobjc方式“(另请参阅该线程上的所有其他消息以供进一步说明)。
重复:http://stackoverflow.com/questions/49137/calling -python-从-AC-节目换分布; http://stackoverflow.com/questions/297112/how-do-i-use-python-libraries-in-c。你可以在任何应用程序中嵌入Python。 – 2009-04-26 01:56:47