【问题标题】:NSTask get notified when a command can't execute "command not found"当命令无法执行“找不到命令”时,NSTask 会收到通知
【发布时间】:2017-06-14 18:43:33
【问题描述】:

我正在尝试从我的应用程序运行终端命令/脚本,一切正常,但是当命令错误且无法执行时,我会得到如下信息:

但是这个“/bin/bash: line...”字符串不在我从任务中得到的输出字符串中,有没有办法在我的应用程序中获取这些错误或以任何方式得到通知?

我的代码

    // Create a new task
    let task: Process = Process()
    task.environment = env
    task.launchPath = "/usr/bin/env"
    task.arguments = ["/bin/bash", "-c", command.scriptCode]

    // Assign output pipes
    let pipe: Pipe = Pipe()
    let outHandle: FileHandle = pipe.fileHandleForReading
    task.standardOutput = pipe

    outHandle.readabilityHandler = { pipe in
        if let line = String(data: pipe.availableData, encoding: String.Encoding.utf8) {
            if line.contains("command not found") {
                // never triggered ????
            } else {
                print("New ouput: \(NSDate() )\(line)")
            }
        } else {
            print("Error decoding data: \(pipe.availableData)")
        }
    }

【问题讨论】:

  • bash 会将消息写入标准错误,因此您可以像捕获task.standardOutput 一样捕获task.standardError
  • 感谢按预期工作,Xcode 只自动完成标准输出:o

标签: swift xcode macos swift4 nstask


【解决方案1】:

您正在寻找的东西是 standardError NSTaskProcess 类的属性。就像使用standardOutput 一样,将管道分配给该属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2014-09-27
    • 2015-12-21
    • 2011-05-13
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    相关资源
    最近更新 更多