gpt4 book ai didi

swift - 终端命令不适用于 Swift

转载 作者:行者123 更新时间:2023-11-30 13:32:19 24 4
gpt4 key购买 nike

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

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

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

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... 的用途。

最佳答案

我怀疑这一行:

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\""

(或类似的东西)。

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

关于swift - 终端命令不适用于 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com