用于与 Python 交互的 Swift 框架。
PythonKit
需要 Swift 5 或更高版本,并且已在 macOS、Linux 和 Windows 上进行过测试。
像这样的 Python 代码
import sys
print(f"Python {sys.version_info.major}.{sys.version_info.minor}")
print(f"Python Version: {sys.version}")
print(f"Python Encoding: {sys.getdefaultencoding().upper()}")
可以通过 PythonKit 在 Swift 中使用以下代码实现
import PythonKit
let sys = try Python.import("sys")
print("Python \(sys.version_info.major).\(sys.version_info.minor)")
print("Python Version: \(sys.version)")
print("Python Encoding: \(sys.getdefaultencoding().upper())")
将以下依赖项添加到您的 Package.swift
清单文件中
.package(url: "https://github.com/pvieito/PythonKit.git", .branch("master")),
PythonKit
可以使用 Swift PM 构建
$ cd PythonKit
$ swift run
[*] Python 3.7
[ ] Version: 3.7.0
Python 库将在运行时加载,PythonKit
将尝试找到系统中可用的最新 Python 版本。您可以使用 PYTHON_VERSION
环境变量强制指定版本,或使用 PYTHON_LIBRARY
指定特定的 Python 库路径或名称。
$ PYTHON_VERSION=3 swift run
[*] Python 3.5
[ ] Version: 3.5.2
$ PYTHON_VERSION=2.7 swift run
[*] Python 2.7
[ ] Version: 2.7.10
$ PYTHON_LIBRARY=libpython3.5.so swift run
[*] Python 3.5
[ ] Version: 3.5.2
$ PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython2.7.so swift run
[*] Python 2.7
[ ] Version: 2.7.10
如果 PythonKit
无法找到并加载 Python 库,您可以设置 PYTHON_LOADER_LOGGING
环境变量,以了解 PythonKit
正在尝试从哪些位置加载库
$ PYTHON_LOADER_LOGGING=TRUE PYTHON_VERSION=3.8 PythonTool
Loading symbol 'Py_Initialize' from the Python library...
Trying to load library at 'Python.framework/Versions/3.8/Python'...
Trying to load library at '/usr/local/Frameworks/Python.framework/Versions/3.8/Python'...
Fatal error: Python library not found. Set the PYTHON_LIBRARY environment variable with the path to a Python library.
PythonKit
是基于 Swift for TensorFlow 项目中的 Python
模块。这两个项目的维护者一直在共同开发它们,目前 PythonKit
作为 Swift for TensorFlow 工具链的一部分分发。PythonKit
有疑问,可以在 Swift for TensorFlow Google Group 或 Swift Forums 上提问。