Py_Initialize undefined error in Xcode while integrating Python in iOS project

161 views Asked by At

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()
    }
}

I am getting error as below enter image description here

This project directory I got from my colleague on whose machine this project runs successfully.

1

There are 1 answers

0
thedp On

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