打开Xcode项目。然后选择“File→Add Packages”,然后输入软件包依赖链接:
https://github.com/pvieito/PythonKit.git
https://github.com/kewlbear/Python-iOS.git
Python-iOS包允许在iOS应用程序中使用python模块。
用法:
import PythonSupport
PythonSupport.initialize()
PythonKit是与Python交互的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())")
调用示例
test.py
#!/usr/bin/python3
#coding=utf8
def hello():
print('hello world')
return 'hello'
swift:
import PythonKit
import PythonSupport
class PythonManager {
func initManager() {
//初始化
PythonSupport.initialize()
//导入sys模块
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())")
print("Python Path: \(sys.path)")
//运行python脚本
PythonSupport.runSimpleString("print('hello')")
//运行test.py文件
let python = Python.import("test")
let result = python.hello()
print(result)
}
}