Trying to run simple Bash command in Swift - 'Couldn't posix_spawn: error 13'

◇◆丶佛笑我妖孽 提交于 2019-12-08 13:07:24

问题


I'm trying to build a MacOS app that can run bash commands from GUI input and have fallen at the first hurdle. I've been using this question's answer as a reference but it doesn't seem to work for me. This is my code:

import Foundation

@IBAction func buttonClicked(_ sender: Any) {
       shell("ls")
}

@discardableResult
func shell(_ args: String...) -> Int32 {
    let task = Process()
    task.launchPath = "/Users/myUser/desktop"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

I've seen others asking about this error but they are getting it for slightly different reasons meaning I can't seem to find a fix for my particular instance of the problem.

Any ideas?

EDIT - Would also be great if someone could give me a hint as to how to get the output of the ls command back into my program, to store as a string for example.


回答1:


For a simple terminal app this is what I used

func shell(_ command: String) -> String {
    let task = Process()
    task.launchPath = "/bin/bash"
    task.arguments = ["-c", command]

    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()

    guard let output = String(data: data, encoding: .utf8) else {
        print("Failed to produce string from \(data)")
        abort()
    }

    return output
}


来源:https://stackoverflow.com/questions/57394288/trying-to-run-simple-bash-command-in-swift-couldnt-posix-spawn-error-13

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!