如何从NSTask读取数据(进程)

时间:2017-11-21 09:10:00

标签: swift macos nstask

@IBAction func startLocalAction(_ sender: NSButton) {
    cmd(cmdStr: ["-c","cd Desktop;ls;git clone https://github.com/Fidetro/Masonry"])

}

@objc func receivedData(notification:NSNotification) {
    let fileHandle = notification.object
    if let handle = fileHandle as? FileHandle {
        let data = handle.availableData
        let result = String.init(data: data, encoding: .utf8)
        print(result)
        handle.waitForDataInBackgroundAndNotify()
    }
}

func cmd(cmdStr:[String]) {
    let outputPipe = Pipe()
    let process = Process()
    process.launchPath = "/bin/bash"
    process.currentDirectoryPath = NSHomeDirectory()
    //        let inputPipe = Pipe()
    process.arguments = cmdStr
    process.standardOutput = outputPipe
    //        process.standardInput = inputPipe
    let fileHandle = outputPipe.fileHandleForReading

    fileHandle.waitForDataInBackgroundAndNotify()
    NotificationCenter.default.addObserver(self, selector: .receivedData, name: NSNotification.Name.NSFileHandleDataAvailable, object: fileHandle)
    process.launch()
    fileHandle.waitForDataInBackgroundAndNotify()
}

输出:

Cloning into 'Masonry'...
remote: Counting objects: 2650, done.        
Receiving objects:   0% (1/2650)   
Receiving objects:   1% (27/2650)   
Receiving objects:   2% (53/2650)   
Receiving objects:   3% (80/2650)   
Receiving objects:   4% (106/2650)   
Receiving objects:   4% (125/2650), 28.01 KiB | 20.00 KiB/s   

我想获得克隆进程百分比,我在终端看到输出,但我不知道如何获得 我尝试Get Notification of task progress from NSTaskGetting process output using NSTask on-the-go?,但未使用

0 个答案:

没有答案