我想在 ios 上运行 python 脚本。 我不想只用 Python 编写整个应用程序的一小部分。
我试图理解 PyObjC,但这并不容易。
你能举个例子吗?我想将以下方法的结果保存在 NSString
变量中。
def doSomething():
someInfos = "test"
return someInfos
最佳答案
下面是调用myModule
中定义的函数的示例。等效的 python 将是:
import myModule
pValue = myModule.doSomething()
print pValue
在 Objective-c 中:
#include <Python.h>
- (void)example {
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
NSString *nsString;
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyString_FromString("myModule");
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, "doSomething");
if (PyCallable_Check(pFunc)) {
pValue = PyObject_CallObject(pFunc, NULL);
if (pValue != NULL) {
if (PyObject_IsInstance(pValue, (PyObject *)&PyUnicode_Type)) {
nsString = [NSString stringWithCharacters:((PyUnicodeObject *)pValue)->str length:((PyUnicodeObject *) pValue)->length];
} else if (PyObject_IsInstance(pValue, (PyObject *)&PyBytes_Type)) {
nsString = [NSString stringWithUTF8String:((PyBytesObject *)pValue)->ob_sval];
} else {
/* Handle a return value that is neither a PyUnicode_Type nor a PyBytes_Type */
}
Py_XDECREF(pValue);
} else {
PyErr_Print();
}
} else {
PyErr_Print();
}
// Clean up
Py_XDECREF(pModule);
Py_XDECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
NSLog(@"%@", nsString);
}
关于python - 在 ios 中运行一个简单的 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11276656/