Swift OSX调用bash脚本

时间:2018-12-04 21:27:43

标签: swift bash

我正在制作一个基本的Mac应用程序,这将使运行一堆bash命令变得容易。 (输入代码,检查正常运行时间等。) 这些是我用bash脚本编写的,并且手动调用,它们效果很好。 我想让我的团队更轻松。

我在Swift中做了一个按钮,调用了IB动作。

然后我对该脚本运行Process()。 然后,我想将对呼叫的响应写到Scrollable文本视图中。

脚本全部位于应用程序代码的文件夹中。说:

~/dev/ourapp/scripts/script1.sh
~/dev/ourapp/scripts/script2.sh
// etc...

然后从cmd行调用它们,它们运行良好。

我的代码是:

func run(_ command: String) -> String? {
        let pipe = Pipe()
    //    let path = Bundle.main.url(forResource: command, withExtension: "sh")
        let filePath = Bundle.main.path(forResource: command, ofType: "sh")

        if(filePath == nil) {
            return  String(format:"Unknown Command: %@", command)
        } else {
            let process = Process()
            process.launchPath = String(format:"/bin/bash %@", filePath!)
            process.standardOutput = pipe
            let fileHandle = pipe.fileHandleForReading
            process.launch()
            return String(data: fileHandle.readDataToEndOfFile(), encoding: .utf8)
        }
    }

然后我在“操作”中通过以下方式调用它:

    @IBAction func CallScript1(_ sender: NSButton) {

//        let response = run("~/dev/ourapp/scripts/script1")
        let response = run("script1")

        server_log.documentView!.insertText(response)

    }

我得到的错误:

  

无法访问启动路径

谢谢

0 个答案:

没有答案
相关问题