Getting Started¶
After having embedded PytoRuntime along with one or multiple Python versions in yout app, the first thing you need is finding the Python framework to be loaded using find(in:). This will search inside the Frameworks directory of the process main bundle by default but you can specify another bundle to look for (useful in app extensions).
import PytoRuntime
let version = Version.find()[0]
The version framework must be prefixed Python3 and the version must be specified in the CFBundleShortVersionString key of Ìnfo.plist. The bundle contains Python as a dynamic library, the standard library and other packages needed by the runtime. Shared extensions, from the standard library or third party packages are shipped as frameworks in the app bundle alongside Python and not inside it unlike the official macOS distribution.
Loading the Interpreter¶
After getting the version bundle, you may want to use the Interpreter class and run(_:with:enableBreakpoints:) function to run code, a script, the shell or the repl. See Script.
let interpreter = Interpreter(version: version)
Task {
do {
let exitCode = try await interpreter.run(.code("print('Hello World!')"))
exit(Int32(exitCode))
} catch {
if let exception = error as? Exception {
if let tb = exception.traceback?.as_text {
fputs("\(tb)\n", stderr)
} else {
fputs("\(exception.type): \(exception.args)\n", stderr)
}
} else if case .killed(let signal) = error as? Interpreter.Error {
fputs("Killed by signal: \(error.localizedDescription)", stderr)
exit(signal+128)
} else {
fputs("\(error.localizedDescription)\n", stderr)
}
exit(1)
}
}
Notice how Python exceptions are converted to Swift as Èxception instances.
Customizing the Interpreter¶
To redirect standard input, output and error, Interpreter exposes standardInput, Ìnterpreter.standardOutput and standardError as Foundation FileHandle values which is essentially a file descriptor from either a pipe, a device or a disk file.
The working directory of the threads owned by the interpreter can be changed with workingDirectory. This works by calling the private pthread_chdir_np function.
To use a virtual environment, see virtualEnvironmentHomeURL.