【问题标题】:Terminal command not working with Swift终端命令不适用于 Swift
【发布时间】:2016-04-05 20:57:56
【问题描述】:

我正在使用此代码运行终端命令。到目前为止,这一直有效。现在它抱怨:

The file /Users/meee/Library/Developer/Xcode/DerivedData/nameOfXCodeProject-baelzqzfuiydshbtbifxkywekybq/Build/Products/Debug/Chrome.app does not exist.

当我尝试运行带有 args 的命令时,它失败了。它在终端中就像一个魅力。可能是什么问题?

let strEx = "open -a /Applications/Google Chrome.app   --args argsToSet=\"MYARGS\""
strEx.runAsCommand()

extension String {
    func runAsCommand() -> String {
        let pipe = NSPipe()
        let task = NSTask()
        task.launchPath = "/bin/sh"
        task.arguments = ["-c", String(format:"%@", self)]
        task.standardOutput = pipe
        let file = pipe.fileHandleForReading
        task.launch()
        if let result = NSString(data: file.readDataToEndOfFile(), encoding: NSUTF8StringEncoding) {
            return result as String
        }
        else {return "--- Unable to initialize string from file data ---"}
    }
}

编辑:这是我现在使用的。

let pipe = NSPipe()
        let task = NSTask()
        task.launchPath = "/bin/sh"
        task.arguments = [ "-c", "open", "-a","/Applications/Google Chrome.app","--args","myargs=ARGS"]
        task.standardOutput = pipe
        let file = pipe.fileHandleForReading
        task.launch()
        if let result = NSString(data: file.readDataToEndOfFile(), encoding: NSUTF8StringEncoding) {
            print(result as String)
        }
        else {print("--- Unable to initialize string from file data ---")}

        for argum in task.arguments!{
            print(argum)
        }

它只是输出 -c, -a... 的用途。

【问题讨论】:

    标签: swift cocoa terminal swift2


    【解决方案1】:

    我怀疑这条线:

    task.arguments = ["-c", String(format:"%@", self)]
    

    正在有效地创建这个命令行:

    "/bin/sh" "-c" "open -a /Applications/Google Chrome.app   --args argsToSet=\"MYARGS\""
    

    当你想要的是:

    "/bin/sh" "-c" "open" "-a" "/Applications/Google Chrome.app"   "--args" "argsToSet=\"MYARGS\""
    

    (或类似的东西)。

    因此,将参数保存为数组,而不是单个字符串。这样做意味着你不需要像\" 这样的东西;事实上,你根本不需要使用引号。

    【讨论】:

    • 感谢您的光临。我对参数数组运气不佳。看起来是这样的:task.arguments = [ "-c", "open", "-a","/Applications/Google Chrome.app","--args","myargs=ARGS"]。什么都没有发生,我不知道为什么。
    猜你喜欢
    • 2020-01-13
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多