通过swift运行python脚本

2024-05-17 16:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我是swift新手,但我正在尝试通过swift代码运行python脚本。这是到目前为止我的代码,但是我一直得到的输出是zsh:permission denied。我不知道如何进行。我是否有能力运行python脚本

我目前的方法

class func runCode(launchPath: String, cmd: [String]) -> String {
        let pipe = Pipe()
        let process = Process()
        process.launchPath = "/bin/zsh"
        process.arguments = ["-c", String(format:"%@", cmd)]
        process.standardOutput = pipe
        let fileHandle = pipe.fileHandleForReading
        process.launch()
        
        return String(data: fileHandle.readDataToEndOfFile(), encoding: .utf8) ?? "Error"
    }

方法调用

print(Shortcuts.runCode(launchPath: "/usr/bin/python", cmd: [contentView.controller.path]))

输出 zsh:2:权限被拒绝:


Tags: 方法脚本cmdstringbinprocesszshswift
1条回答
网友
1楼 · 发布于 2024-05-17 16:01:47

看起来您正在运行的进程最终是/bin/zsh -c [contentView.controller.path],也就是说,您实际上根本没有运行Python。请注意,在runCode方法中实际上没有使用launchPath参数

在我看来,你应该这样做:

let pipe = Pipe()
let process = Process()
process.launchPath = "/usr/bin/python"
process.arguments = [String(format:"%@", contentView.controller.path)]
process.standardOutput = pipe
let fileHandle = pipe.fileHandleForReading
process.launch()

return String(data: fileHandle.readDataToEndOfFile(), encoding: .utf8) ?? "Error"

我没有将它放在函数中,因为我不确定runCode函数还有什么用途,但这应该适用于您的特定示例

相关问题 更多 >