【发布时间】:2017-03-06 09:58:55
【问题描述】:
如何使用 Swift 从可可应用程序运行 shell 脚本?
我有一个 shell 脚本 file.sh,我想在我的 cocoa 应用程序中运行它。如何使用 Swift 做到这一点?
任何帮助表示赞赏! :)
【问题讨论】:
标签: swift shell cocoa terminal
如何使用 Swift 从可可应用程序运行 shell 脚本?
我有一个 shell 脚本 file.sh,我想在我的 cocoa 应用程序中运行它。如何使用 Swift 做到这一点?
任何帮助表示赞赏! :)
【问题讨论】:
标签: swift shell cocoa terminal
您可以为此使用NSTask (API reference here)。
NSTask 需要(除其他外)launchPath,它指向您的脚本。它还可以采用arguments 的数组,当您准备好启动任务时,您可以调用launch()。
所以...类似于:
var task = NSTask()
task.launchPath = "path to your script"
task.launch()
正如@teo-sartory 在他下面的评论中指出的NSTask 现在是Process,记录在案的here
命名和调用方式也发生了一些变化,这里有一个如何使用Process调用ls的示例
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/ls")
try? process.run()
如果您希望更好地访问/更好地控制调用的输出,可以附加Pipe(记录在here)。
这里有一个简单的例子来说明如何使用它:
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/ls")
// attach pipe to std out, you can also attach to std err and std in
let outputPipe = Pipe()
process.standardOutput = outputPipe
// away we go!
try? process.run()
//read contents as data and convert to a string
let output = outputPipe.fileHandleForReading.readDataToEndOfFile()
let str = String(decoding: output, as: UTF8.self)
print(str)
你可以看看:
希望对你有所帮助。
【讨论】:
我在网上找到了这个功能:
@discardableResult
private func shell(_ args: String) -> String {
var outstr = ""
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", args]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
outstr = output as String
}
task.waitUntilExit()
return outstr
}
来电:
shell("/pathToSh/file.sh")
【讨论】:
/bin/sh -c sh /pathToSh/file.sh 这显然不起作用..
shell("open /Folder/") 重新测试过,效果很好。也许你应该检查一下-c 做了什么...stackoverflow.com/questions/3985193/what-is-bin-sh-c
open 从外壳打开文件,不要更改目录。你的方法启动bash -c,这意味着它将启动bash并在-c之后执行命令,所以它就像bash -c bash file.sh一样,它不起作用。
sh 是用来运行脚本的……不过你的版本也可以。