首页 > 解决方案 > 通过进程运行脚本 - 找不到脚本

问题描述

我正在尝试使用 Swift 5 从 Mac OS/X 应用程序运行脚本,但是在运行该过程时,它无法找到脚本(我确信我遗漏了一些明显的东西,但看不到什么)

我尝试只传入脚本名称、脚本的完整 url 以及 task.currentDirectoryURL 已完成和未完成;但仍然找不到脚本

public func run() -> Bool {

    let task = Process()
    // scriptURL    URL         "file:///Users/phil/Documents/My%20Scripts/"
    // name         String      "myscript"
    task.executableURL = scriptURL.appendingPathComponent(name).appendingPathExtension("sh")
    task.currentDirectoryURL = scriptURL
    task.arguments = []
    let outputPipe = Pipe()
    let errorPipe = Pipe()

    task.standardOutput = outputPipe
    task.standardError = errorPipe

    do {
        try task.run()
        let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
        print(String(decoding: outputData, as: UTF8.self))
        return true
    } catch let error as NSError {
        print(error.localizedDescription)
        let handle = errorPipe.fileHandleForReading
        let errorData = handle.readDataToEndOfFile()
        print(String(decoding: errorData, as: UTF8.self))
        return false
    }
}

当 task.run() 被调用时,它被 Catch 捕获并且 NSError 返回“文件“myscript.sh”不存在。”,但它确实存在于 ScriptsURL 文件夹中。

标签: swiftprocess

解决方案


推荐阅读