在NSTask中设置启动路径时如何捕获错误 [英] How to catch error when setting launchpath in NSTask
问题描述
我试图在Mac(10.10)上使用swift 2运行命令行工具:
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()
// NSPipe() stuff to catch output
task.waitUntilExit()
// never reached
if (task.terminationStatus != 0){
NSLog("uh oh")
}
由于路径错误,我的程序死于launch path not accessible
.但是,我不知道如何捕获此错误.在task.launch()
周围使用do { try } catch {}
无效,因为它不会引发异常,因此查看terminationStatus
也是无效的,因为它从未到达过.
Since the path is wrong, my program dies with launch path not accessible
. However, I don't know, how to catch this error. Using do { try } catch {}
around task.launch()
does not work, because it does not throw an exception, looking at the terminationStatus
is also not working, since it is never reached.
如何找到错误的launchPath
?
Apple Swift版本2.1.1(swiftlang-700.1.101.15 clang-700.1.81) 目标:x86_64-apple-darwin14.5.0
Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81) Target: x86_64-apple-darwin14.5.0
推荐答案
,没有机会捕获运行时异常.使用try/catch可以从出现错误的错误中恢复,而不是从运行时异常中恢复.您可以创建自己的异常处理程序,但是仍然无法从中恢复.尝试从NSTask中以命令作为参数,使用一些常见的外壳吃午餐,然后使用管道将os错误返回给您自己的代码.
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 ?? "")
将打印
/bin/bash: unknown: command not found
这篇关于在NSTask中设置启动路径时如何捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!