xcode 在ios中运行一个简单的python脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11276656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
run a simple python script in ios
提问by Matt3o12
I want to run a python script on ios. I don't want to write the whole Application in Python just a little part of it.
我想在 ios 上运行一个 python 脚本。我不想用 Python 编写整个应用程序,只是其中的一小部分。
I have tried to understand PyObjC but it is not that easy.
我试图理解 PyObjC,但这并不容易。
Could you give me an example, please? I would like to save the result for the following method in a NSString
variable.
请你给我举个例子好吗?我想将以下方法的结果保存在一个NSString
变量中。
def doSomething():
someInfos = "test"
return someInfos
回答by chown
Here is an example of calling a function defined in myModule
. The equivient python would be:
下面是一个调用 中定义的函数的例子myModule
。等效的蟒蛇将是:
import myModule
pValue = myModule.doSomething()
print pValue
In Objective-c:
在 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);
}
For much more documentation check out: Extending and Embedding the Python Interpreter
有关更多文档,请查看:扩展和嵌入 Python 解释器