3

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.

1
  • 1
    "It seems like most of the info out there is outdated" is pretty vague. What info did you find exactly? Why is it outdated? Did you leave a comment at existing answers and ask for updates? Commented Nov 25, 2015 at 15:00

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.