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

标签 python xcode methods

我想在 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);
}

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

关于python - 在 ios 中运行一个简单的 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11276656/

相关文章:

python - 自动为 Django 模型中的每个选项添加常量

ios - 更改启动画面,复制启动画面

ios - 在 WatchOS 中以模态呈现的界面的右上角设置标题

C++ 函数写得不好,不知道如何简化它[初学者]

java - Java 扑克骰子程序

java - 使用同一类内部的外部方法设置构造函数变量

python - '属性错误 : 'tuple' object has no attribute 'lower' ' - Why doesn't the '.lower()' method doesn't work here in Python?

python - 我需要如何将 sql 插入、通用值、哪些列和值可变化?

python - Windows 中的路径和权限

iphone - AppDelegate 未被调用