首页 > 解决方案 > 我无法使用 PythonKit 在 Xcode 11 中导入 Python 模块

问题描述

我现在正在使用 Swift 包管理器。

使用它,我将 PythonKit 导入到我的 Swift 项目中。

我现在无法使用 PythonKit 导入 Python 模块。

它要求我设置 PYTHON_LIBRARY 路径,但我不知道该怎么做。

谁能帮我?

//
//  ViewController.swift
//  VideoStream
//
//  Created by HeRo Gold on 7/20/19.
//  Copyright © 2019 TopAce. All rights reserved.
//

import UIKit
import PythonKit

let sys = Python.import("sys")

class ViewController: UIViewController {

    @IBOutlet weak var netflixView: WKWebView!
    let netflixURL = URL(string: "https://www.netflix.com/login")

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let pymsl = try Python.import(name: "pymsl")

        print("Python \(sys.version_info.major).\(sys.version_info.minor)")
        print("Python Version: \(sys.version)")
        print("Python Encoding: \(sys.getdefaultencoding().upper())")
    }
}

这是我在 iPhone 上运行 iOS 应用程序时出现的错误消息

致命错误:未找到 Python 库。使用 Python 库的路径设置 PYTHON_LIBRARY 环境变量。:文件 /Users/herogold/Library/Developer/Xcode/DerivedData/VideoStream-cjytedddvtktmybclqlztmfdbekk/SourcePackages/checkouts/PythonKit/PythonKit/PythonLibrary.swift,第 40 行
2019-07- 20 23:55:00.967869+0800 VideoStream[31841:170718] 致命错误:找不到 Python 库。使用 Python 库的路径设置 PYTHON_LIBRARY 环境变量。:文件 /Users/herogold/Library/Developer/Xcode/DerivedData/VideoStream-cjytedddvtktmybclqlztmfdbekk/SourcePackages/checkouts/PythonKit/PythonKit/PythonLibrary.swift,第 40 行

标签: pythoniosswiftxcode

解决方案


第一个 SO 答案,所以请原谅格式化/等。我自己经历了一段时间,有不同的错误,但通常是相同的问题。我希望这对您有所帮助——需要考虑的一些资源:

1) Pyto ——iOS/Catalyst 的完全嵌入式 Python 环境;使用 LXML 和 Python 库移植说明<- 这是您在 iOS 上运行后需要建模的内容,我的解决方案适用于 Mac Catalyst (预装 Python 的 Mac)

2) Python Kit Tutorial——这家伙一步一步地经历了如何实现PythonKit

这对我有用:

1)在Signing and Capabilities中禁用App Sandbox:

在 App Sandbox 的右上角,在 Signing & Capabilities 下有一个“X”,点击它来移除 App Sandbox

2)在签名和功能下的“强化运行时”中:选中“禁用库验证”

禁用库验证复选框的图像

现在,我还没有根据这些规定向 App Store 提交应用程序,但至少我的 python 文件和库加载/构建/运行!


2020 年 5 月 15 日更新:

对于 Mac Developer Distribution,您必须对应用程序中包含的所有 .so 或 .dylib 以及 Python Interpreter 和 bin 文件夹进行签名。使用 dev 完成后,我制作了一个快速 bash 脚本来运行每个脚本。

function signThese() {
        find . -name "*.$1" | while read line; do
                codesign --force --verbose=4 --options=runtime --timestamp --sign "Developer ID Application: [INSERT YOUR CERT HERE]" $line
        done
}


这将允许您在签名和功能中使用 AppSandbox,以及所有强化运行时选项(如不禁用库验证)。


推荐阅读