我正在使用此代码运行终端命令。到目前为止,这一直有效。现在它抱怨:
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 ...用于。
答案 0 :(得分:0)
我怀疑这一行:
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\""
(或类似的东西)。
因此,将参数保存为数组,而不是单个字符串。这样做意味着你不需要像\"
这样的东西;事实上,你根本不需要使用引号。