forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInitializePython.swift
More file actions
42 lines (34 loc) · 1.28 KB
/
InitializePython.swift
File metadata and controls
42 lines (34 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import Foundation
import Python
import PythonKit
import PythonHelper
func initializePython() {
guard let sitePackagePath = Bundle.main.path(forResource: "site-packages", ofType: nil),
let stdLibPath = Bundle.main.path(forResource: "python-stdlib", ofType: nil),
let libDynloadPath = Bundle.main.path(
forResource: "python-stdlib/lib-dynload",
ofType: nil
)
else { return }
setenv("PYTHONHOME", stdLibPath, 1)
setenv("PYTHONPATH", "\(stdLibPath):\(libDynloadPath):\(sitePackagePath)", 1)
// Initialize python
Py_Initialize()
// Immediately release the thread, so that we can ensure the GIL state later.
// We may not recover the thread because all future tasks will be done in the Python Thread.
let _ = PyEval_SaveThread()
// Setup GIL state guard.
PythonHelper.PyGILState_Guard = { closure in
let gilState = PyGILState_Ensure()
try closure()
PyGILState_Release(gilState)
}
Task {
// All future task should run inside runPython.
try await runPython {
let sys = Python.import("sys")
print("Python Version: \(sys.version_info.major).\(sys.version_info.minor)")
}
}
}
let queue = DispatchQueue(label: "")