Swift框架,用于与Python交互。
类似这样的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 = 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"),
由于Python库在运行时由 PythonKit 加载,它将尝试查找系统中可用的最新Python版本。你可以使用 PYTHON_VERSION
环境变量强制指定版本,或使用 PYTHON_LIBRARY
环境变量指定特定的Python库路径或名称。
$ PYTHON_VERSION=3 swift run
[*] Python 3.5
$ PYTHON_VERSION=2.7 swift run
[*] Python 2.7
$ PYTHON_LIBRARY=libpython3.5.so swift run
[*] Python 3.5
$ PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython2.7.so swift run
[*] Python 2.7
如果 PythonKit 无法找到并加载Python库,你可以设置 PYTHON_LOADER_LOGGING
环境变量以了解 PythonKit 尝试从哪些位置加载库。
$ PYTHON_LOADER_LOGGING=TRUE PYTHON_VERSION=3.8 swift run
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.
Python
模块构建的。