在ios中运行一个简单的python脚本

我想在ios上运行python脚本.
我不想在Python中编写整个Application的一小部分.

我试图了解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);
}

有关更多文档,请查看:Extending and Embedding the Python Interpreter

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...