简体   繁体   中英

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). If I run the Application with Apple+R from within Xcode the Progress of this Terminal command is refreshed as it should. 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:

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!)
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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