Swift使用PythonKit调用Python

打开Xcode项目。然后选择"File→Add Packages",然后输入软件包依赖链接:

https://github.com/pvieito/PythonKit.git

https://github.com/kewlbear/Python-iOS.git

Python-iOS包允许在iOS应用程序中使用python模块。

用法:

Swift 复制代码
import PythonSupport

PythonSupport.initialize()

PythonKit是与Python交互的Swift框架。

用法:

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

python 复制代码
#!/usr/bin/python3
#coding=utf8

def hello():
    print('hello world')
    return 'hello'

swift:

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)
    }
}
相关推荐
2501_915921435 小时前
iOS App 开发阶段性能优化,观察 CPU、内存和日志变化
android·ios·性能优化·小程序·uni-app·iphone·webview
游戏开发爱好者86 小时前
在 iOS 开发、测试与上架过程中 如何做证书管理
android·ios·小程序·https·uni-app·iphone·webview
ii_best6 小时前
按键精灵安卓/IOS手机助手 × 手机按键 App:1 分钟搞定设备连接(超详细教程)
android·ios·智能手机·自动化·编辑器
2501_916007477 小时前
在没有 Mac 的情况下完成 iOS 应用上架 App Store
android·macos·ios·小程序·uni-app·iphone·webview
TheNextByte17 小时前
iPhone存储空间已满?如何轻松释放iPhone空间?
android·ios·iphone
—Qeyser15 小时前
Flutter 颜色完全指南
android·flutter·ios
2501_9160088917 小时前
iOS 上架需要哪些准备,账号、Bundle ID、证书、描述文件、安装测试及上传
android·ios·小程序·https·uni-app·iphone·webview
Zender Han1 天前
Flutter Android 启动页 & App 图标替换(不使用任何插件的完整实践)
android·flutter·ios
—Qeyser1 天前
Flutter CustomScrollView 自定义滚动视图 - 完全指南
android·flutter·ios
—Qeyser1 天前
Flutter ListView 列表组件完全指南
android·flutter·ios