Example for using PythonKit for Swift.
Arguments: <path to directory with Python scripts> <base name of Python script>.
It then uses the function replaceAllAs
in the Python script to replace all “a” in the text “Aha” by “x”:
def replaceAllAs(text):
return text.replace("a", "x")
As a prerequisite, PythonKit
has to be added as a dependency of your Swift package, see the Package.swift
file.
Then, in your Swift program:
Import PythonKit
:
import PythonKit
Import the Python script, using pythonScripts
as the path to directory containing your Python script, and pythonModule
as the base name of your Python script:
let sys = Python.import("sys")
sys.path.append(pythonScripts)
let script = try Python.attemptImport(pythonModule)
You should not need to use let sys = Python.import("sys")
and sys.path.append(pythonScripts)
if your Python script has been installed as part of a package.
Call a function of the Python script:
let changedText = String(script.replaceAllAs(text))
You set the environment variable PYTHON_LIBRARY
to reference the according CPython library file, on Linux e.g.:
export PYTHON_LIBRARY=/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu/libpython3.6.so
Use find /usr/lib -name *libpython*.so
to search for an appropriate Python library on Linux. On macOS, an according library file has the dylib
extension.
You may not need to set this environment variable on macOS. But you might have to set "Enable Hardened Runtime" to "No" in the macOS settings when using a Python version installed by you.
To use a specific Python environment, reference the Python library file inside the environment.
When using a Python script via PythonKit, Python might run with some "missing" settings. When you need to read UTF-8 encoded files, you need to:
- set
PYTHONIOENCODING
:export PYTHONIOENCODING=utf-8
on macOS/Linux, - add the appropriate argument to some calls, e.g.
open(path, 'r', encoding="utf-8")
instead of justopen(path, 'r')
.
Note that CPython has the "global interpreter lock" (GIL), so calling into Python scripts concurrently should not work. The GIL might be removed in future versions of CPython (status: end of 2022).