[英]Redirect the output of Terminal command to TextView
I want to execute a Terminal command in my Application and redirect the Terminal output of this command to a TextView (content_scroller).我想在我的应用程序中执行一个终端命令,并将这个命令的终端输出重定向到一个 TextView (content_scroller)。 If I run the Application with Apple+R from within Xcode the Progress of this Terminal command is refreshed as it should.
如果我从 Xcode 中使用 Apple+R 运行应用程序,则此终端命令的进度会按原样刷新。 But ... If I started the Application the normal way only the first line of terminal output is shown but there is no refresh/new lines anymore.
但是......如果我以正常方式启动应用程序,则只显示第一行终端输出,但不再有刷新/新行。 But why?
但为什么? Is there a way to loop the request of the actual output?
有没有办法循环实际输出的请求? Here is mit Swift 5 Code:
这是 MIT Swift 5 代码:
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: .utf8) {
DispatchQueue.main.sync {
self.content_scroller.string += line
self.content_scroller.scrollToEndOfDocument(nil)
}
}
process.waitUntilExit()
filelHandler.readabilityHandler = nil
}
Should be able to direct output straight to text view if I understand your question correctly.如果我正确理解您的问题,应该能够直接输出到文本视图。 Something like the following outputs an error (I didn't test it.)
像下面这样的输出错误(我没有测试它。)
import Cocoa
func syncShellExec(path: String, args: [String] = []) {
var status : Int32
var dataRead : Data
var stringRead :String?
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = [path] + args
let outputPipe = Pipe()
let txtView = NSTextView()
let fileHandler = outputPipe.fileHandleForReading
process.standardOutput = outputPipe
process.launch()
process.waitUntilExit()
status = process.terminationStatus
dataRead = fileHandler.readDataToEndOfFile()
stringRead = String.init(data: dataRead, encoding: String.Encoding.utf8)
if (status != 0) {
txtView.string.append("Terminated with error.\n")
txtView.string.append(stringRead!)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.