在ios中运行一个简单的python脚本 [英] run a simple python script in ios

查看:1043
本文介绍了在ios中运行一个简单的python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在ios上运行python脚本. 我不想只用Python编写整个应用程序的一小部分.

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.

我试图了解PyObjC,但这并不容易.

I have tried to understand PyObjC but it is not that easy.

能给我一个例子吗?我想将以下方法的结果保存在NSString变量中.

Could you give me an example, please? I would like to save the result for the following method in a NSString variable.

def doSomething():
   someInfos = "test"
   return someInfos

推荐答案

这里是调用myModule中定义的函数的示例.等价的python是:

Here is an example of calling a function defined in myModule. The equivient python would be:

import myModule
pValue = myModule.doSomething()
print pValue

在Objective-c中:

In 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解释器

For much more documentation check out: Extending and Embedding the Python Interpreter

这篇关于在ios中运行一个简单的python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆