Call Python code from an existing project written in Swift

In Swift 4.2 there was an approved feature to allow dynamic languages to be ported directly into swift

https://github.com/apple/swift-evolution/blob/master/proposals/0195-dynamic-member-lookup.md

Will look similar to:

  // import pickle
  let pickle = Python.import("pickle")

  // file = open(filename)
  let file = Python.open(filename)

  // blob = file.read()
  let blob = file.read()

  // result = pickle.loads(blob)
  let result = pickle.loads(blob)

I found this excellent and up to date gist that walks you through a complete solution: https://github.com/ndevenish/Site-ndevenish/blob/master/_posts/2017-04-11-using-python-with-swift-3.markdown

If you can get away with just using NSTask to launch a Python process, that's a pretty good option too.


In swift 5 you can try PythonKit framework.

Here's example of the usage:

import PythonKit

let sys = try Python.import("sys")

print("Python \(sys.version_info.major).\(sys.version_info.minor)")
print("Python Version: \(sys.version)")
print("Python Encoding: \(sys.getdefaultencoding().upper())")

Tags:

Python

Swift