在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.