How to catch error when setting launchpath in NSTask

后端 未结 3 1335
野的像风
野的像风 2021-01-18 02:58

I am trying to run a commandline tool using swift 2 on a mac (10.10):

let task = NSTask()
task.launchPath = \"/path/to/wrong/binary\"
task.launch()

// NSPip         


        
3条回答
  •  耶瑟儿~
    2021-01-18 03:36

    unfortunately, there is no chance to catch runtime exceptions. with try / catch you can recovery from trowing error, not from runtime exception. you can create you own exception handler, but you are still not able to recover from it. try to lunch from NSTask some common shell with command as a parameter and next use a pipe to return os errors to you own code.

    import Foundation
    
    let task = Process()
    let pipe = Pipe()
    task.launchPath = "/bin/bash"
    task.arguments = ["-c","unknown"]
    task.standardOutput = pipe
    task.launch()
    let handle = pipe.fileHandleForReading
    let data = handle.readDataToEndOfFile()
    let dataString = String(data: data, encoding: .utf8)
    print(dataString ?? "")
    

    will print

    /bin/bash: unknown: command not found
    

提交回复
热议问题