尝试在Swift中运行简单的Bash命令-'无法posix_spawn:错误13' [英] Trying to run simple Bash command in Swift - 'Couldn't posix_spawn: error 13'

查看:138
本文介绍了尝试在Swift中运行简单的Bash命令-'无法posix_spawn:错误13'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个MacOS应用程序,该应用程序可以从GUI输入中运行bash命令,并且遇到了第一个障碍.我一直在使用此问题的答案作为参考,但似乎不适用于我.这是我的代码:

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.

有什么想法吗?

编辑-如果有人可以给我一个提示,告诉我如何将ls命令的输出返回到我的程序中,例如以字符串形式存储,那也很棒.

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.

推荐答案

对于一个简单的终端应用程序,这就是我所使用的

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
}

这篇关于尝试在Swift中运行简单的Bash命令-'无法posix_spawn:错误13'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆