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

在Swift OS X应用中使用Python模块

如何在OS X应用程序中集成Python模块,以便可以从Swift调用Python?似乎大多数信息都已过时,我想确保自己走的路正确.

解决方法:

答案取决于您的Python的复杂程度以及您的需求.通过Swift中的C接口仅使用Python的超级基本示例(请确保添加Python.framework):

import Python

Py_Initialize()

let a = PyInt_FromLong(1)
let b = PyInt_FromLong(2)
let c = PyNumber_Add(a, b)

let result = PyInt_AsLong(c)
print("Result is \(result)") // will print 'Result is 3'

对于更复杂的事情,它变得更加复杂:

import Python

Py_Initialize()

// call urllib.urlopen('http://icanhazip.com').read()
let module = PyImport_Import(PyString_FromString("urllib"))
let urlOpenFunc = PyObject_GetAttrString(module, "urlopen")
if urlOpenFunc != nil && PyCallable_Check(urlOpenFunc) == 1 {
    let args = PyTuple_New(1)
    PyTuple_SetItem(args, 0, PyString_FromString("http://icanhazip.com"))
    let openCall = PyObject_CallObject(urlOpenFunc, args)
    let readCall = PyObject_CallObject(PyObject_GetAttrString(openCall, "read"), nil)
    if readCall != nil {
        if let result = String.fromCString(PyString_Asstring(readCall)) {
            print("My IP is \(result)")
        } else {
            print("Failed")
        }
    }
}

如果您想在Python中做一些认真的工作,请确保Swift调用的接口超级简单,或者使用PyObjC.

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

相关推荐