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.
-
1Apple doesn't allow apps to be written, in any part, in languages besides Obj-C and Swift. You're not likely to find any luck in this endeavour (and even if you find a hacky solution, it wouldn't be allowed on the App Store).Hayden Schiff– Hayden Schiff2015-08-10 19:33:15 +00:00Commented Aug 10, 2015 at 19:33
-
1In the deleted answer (seriously, we're deleting answers now that contain a helpful link to an article?), there's a helpful link for OS X at least: practicalswift.com/2014/06/25/…John Goering– John Goering2015-08-11 06:29:18 +00:00Commented Aug 11, 2015 at 6:29
-
@oxguy3 i don't think that' necessarily true. Checkout this doc from apple -developer.apple.com/library/ios/technotes/tn2328/_index.html-Shaun– Shaun2015-08-14 17:04:52 +00:00Commented Aug 14, 2015 at 17:04
4 Answers
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())")
2 Comments
os.chdir() and os.getcwd() to get to the directory where my module is installed, but it fails loading the actual module.sys.path.append(), but I still can't load my custom module. I can load it from the terminal, so the module should be fine.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.
1 Comment
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)
2 Comments
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