Reputation: 2257
I am trying to integrate Python in iOS app.
Here is the contentview file
import SwiftUI
import Python
import PythonKit
struct ContentView: View {
@State private var showingSheet = false
var body: some View {
var name = ""
Button("Run Python") {
showingSheet.toggle()
if let path = Bundle.main.path(forResource: "Python/Resources", ofType: nil) {
setenv("PYTHONHOME",path, 1)
setenv("PYTHONPATH",path, 1)
}
let api = Python.import("foo")
name = String(api.hello())!
}
.sheet(isPresented: $showingSheet) {
SecondView(name: name)
}
}
}
App file which calls contentview
import SwiftUI
import Python
@main
struct pytestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
func pleaseLinkPython() {
Py_Initialize()
}
}
This project directory I got from my colleague on whose machine this project runs successfully.
Upvotes: 1
Views: 221
Reputation: 8508
I believe your problem is with this part "Python/Resources".
You need the python-stdlib
to appear in Build Phase
's Copy Bundle Resources
. And then do this:
import Python
guard let stdLibPath = Bundle.main.path(forResource: "python-stdlib", ofType: nil) else { return }
guard let libDynloadPath = Bundle.main.path(forResource: "python-stdlib/lib-dynload", ofType: nil) else { return }
setenv("PYTHONHOME", stdLibPath, 1)
setenv("PYTHONPATH", "\(stdLibPath):\(libDynloadPath)", 1)
Py_Initialize()
// we now have a Python interpreter ready to be used
I wrote an article elaborating step-by-step how to embed a Python interpreter in a MacOS / iOS app. I'll live it here for anyone in the future having trouble with this topic: https://medium.com/swift2go/embedding-python-interpreter-inside-a-macos-app-and-publish-to-app-store-successfully-309be9fb96a5
Upvotes: 0