gpt4 book ai didi

swift - FileHandler 输出有更多缓冲区?

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

我有以下代码:

func syncShellExec(path: String, args: [String] = []) {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = [path] + args
let outputPipe = Pipe()
let filelHandler = outputPipe.fileHandleForReading
process.standardOutput = outputPipe
process.launch()

filelHandler.readabilityHandler = { pipe in
let data = pipe.availableData
if let line = String(data: data, encoding: String.Encoding.utf8) {
DispatchQueue.main.sync {
self.output_window.string += line
self.output_window.scrollToEndOfDocument(nil)
}
} else {
print("Error decoding data: \(data.base64EncodedString())")
}
}
process.waitUntilExit()
filelHandler.readabilityHandler = nil
}

如果达到约 330.000 个字符的回合数,输出将立即停止。有没有办法增加此操作的缓冲区?

最佳答案

有两个问题:

  • 进程可能会在从管道中读取所有数据之前终止。
  • 您的函数会阻塞主线程,因此 UI 最终会卡住。

类似于How can I tell when a FileHandle has nothing left to be read?您应该异步等待进程终止,并等待管道上的“文件结束”:

func asyncShellExec(path: String, args: [String] = []) {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = [path] + args
let outputPipe = Pipe()
let filelHandler = outputPipe.fileHandleForReading
process.standardOutput = outputPipe
process.launch()

let group = DispatchGroup()
group.enter()
filelHandler.readabilityHandler = { pipe in
let data = pipe.availableData
if data.isEmpty { // EOF
filelHandler.readabilityHandler = nil
group.leave()
return
}

if let line = String(data: data, encoding: String.Encoding.utf8) {
DispatchQueue.main.sync {
self.output_window.string += line
self.output_window.scrollToEndOfDocument(nil)
}
} else {
print("Error decoding data: \(data.base64EncodedString())")
}
}

process.terminationHandler = { process in
group.wait()
DispatchQueue.main.sync {
// Update UI that process has finished.
}
}
}

关于swift - FileHandler 输出有更多缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57904592/

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