How can I integrate a Python module in an OS X app so I can call Python from Swift? It seems like most of the info out there is outdated and I want to make sure I'm on the right path.
The answer depends on how complex your Python is going to be, and what you need in return. Super basic example of just using Python through the C interface in Swift (be sure to add 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'
For something more complicated, it gets more complicated:
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")
}
}
}
If you want to do some serious work in Python, either make sure the interface called by Swift is super-duper simple, or use PyObjC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With