微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐