首页 > 解决方案 > 通过 bash 从 swift 执行 python:“无法打开文件...[Errno 1] 不允许操作”

问题描述

我正在学习如何为 mac 制作应用程序,并且我开始使用一个应用程序来管理我的许多不和谐机器人。本质上,目标是有许多开关来打开和关闭机器人,这需要为机器人执行 python 文件,使用discord.py. 我读到了一个PythonKit用于 swift 的模块,但是当我尝试从使用它的文件中运行一个不和谐的机器人时,构建不断失败,所以我决定使用 bash shell 来执行 python。这是我使用 bash shell 命令的快速代码:

func shell(_ command: String) -> String {
        let task = Process()
        let pipe = Pipe()

        task.standardOutput = pipe
        task.standardError = pipe
        task.arguments = ["-c", command]
        task.launchPath = "/bin/zsh"
        task.launch()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)!

        return output
    }func shell(_ command: String) -> String {
        let task = Process()
        let pipe = Pipe()

        task.standardOutput = pipe
        task.standardError = pipe
        task.arguments = ["-c", command]
        task.launchPath = "/bin/zsh"
        task.launch()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)!

        return output
    }

然后我调用shell("/usr/local/bin/python3.9 path/to/file.py"),并让它将输出打印到控制台。这是输出: /usr/local/bin/python3.9: can't open file 'path/to/file.py': [Errno 1] Operation not permitted. 我从 AppCode 和 Xcode 运行它,并确保为这两个应用程序提供全盘访问权限,并确保终端全盘访问权限。另外,我尝试/usr/local/bin/python3.9 path/to/file.py在我的终端中运行,它工作正常。这里发生了什么?为什么 swift 不能在 bash shell 中打开这个文件,而我可以?我该怎么做才能修复它?如果您需要更多信息,请告诉我(如果您认为 PythonKit 是答案,我会从中发送构建错误信息以调试该过程)谢谢!

标签: swiftxcodebash

解决方案


Yonatan Vainer 是对的,原来沙盒在权利文件中是打开的,所以我不得不将它设置为关闭,这修复了它。


推荐阅读