I need a way to call Python code from Swift on an Apple platform. A library would be ideal. I’ve done a considerable amount of Google searching, and the closest material I found is for Objective-C.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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())")
Method 2
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.
Method 3
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)
Method 4
If anyone is ever interested in calling python from swift, here is some helpful material I found:
- U the python framework – https://developer.apple.com/library/ios/technotes/tn2328/_index.html
- PyObjC (a little more challenging) –
- Cobbal – https://github.com/cobbal/python-for-iphone
- Python docs (you would need to make C-Swift bridge)
Most of it is for Objective-c, but if you need to use swift you can easily just create an ObjC-Swift bridge (super-super easy) – Lookup the apple docs
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0