简体   繁体   English

如何使用 Swift 从可可应用程序运行 shell 脚本?

[英]How to run a shell script from cocoa application using Swift?

How can I run a shell script from cocoa application using Swift?如何使用 Swift 从可可应用程序运行 shell 脚本?

I have a shell script file.sh that I want to run from within my cocoa application.我有一个 shell 脚本 file.sh,我想在我的可可应用程序中运行它。 How can I do this using Swift?我怎样才能使用 Swift 做到这一点?

Any help appreciated!任何帮助表示赞赏! :) :)

Pre Swift 3斯威夫特 3 之前

You can use NSTask ( API reference here ) for this.您可以NSTask使用NSTask此处API 参考)。

A NSTask takes (among other things) a launchPath which points to your script. NSTask需要(除其他外)一个指向您的脚本的launchPath It can also take an array of arguments and when you are ready to launch your task, you call launch() on it.它还可以接受一组arguments ,当您准备好启动任务时,您可以对其调用launch()

So...something along the lines of:所以......类似的东西:

var task = NSTask()
task.launchPath = "path to your script"
task.launch()

Post Swift 3发布斯威夫特 3

As @teo-sartory points out in his comment below NSTask is now Process , documented here正如@teo-sartory 在他下面的评论中NSTask现在是Process ,记录在这里

The naming and way you call it has changed a bit as well, here is an example of how to use Process to call ls命名和调用方式也发生了一些变化,这里是如何使用Process调用ls的示例

let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/ls")
try? process.run()

If you want better access to/more control over the output from your invocation, you can attach a Pipe (documented here ).如果您想更好地访问/更多地控制调用的输出,您可以附加一个Pipe在此处记录)。

Here is a simple example of how to use that:这是一个如何使用它的简单示例:

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)

Would you like to know more你想知道更多吗

You can have a look at:你可以看看:

Hope that helps you.希望能帮到你。

I found this function on the web:我在网上找到了这个功能:

@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
}

Here's the call:这是电话:

shell("sh /pathToSh/file.sh")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM