gpt4 book ai didi

xcode - OS X 从 shell 返回到 Xcode swift

转载 作者:行者123 更新时间:2023-11-28 11:22:40 24 4
gpt4 key购买 nike

我有调用 shell 的代码。 Shell 对参数进行一些测试,如果通过,它就会运行。现在,我将任何错误发布到日志文件中,但想将它们返回到我的 swift 程序中......

    let bundle = NSBundle.mainBundle()
let cmd = bundle.pathForResource("model", ofType: "sh")
let task = NSTask()
task.launchPath = cmd
task.arguments = [ "\(arg1.stringValue)", "\(arg2.stringValue)" ]
task.launch()

这行得通,但是如何在不读取在 shell 中创建的日志文件的情况下获取 shell 的输出。

最佳答案

遇到这个。希望对您有所帮助。

http://practicalswift.com/2014/06/25/how-to-execute-shell-commands-from-swift/

#!/usr/bin/env xcrun swift -i

import Foundation

let task = NSTask()
task.launchPath = "/bin/echo"
task.arguments = ["first-argument", "second-argument"]

let pipe = NSPipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)

print(output)
assert(output == "first-argument second-argument\n")

在 github 上发布的项目也可能有用:

https://github.com/kareman/SwiftShell

关于xcode - OS X 从 shell 返回到 Xcode swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26089268/

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