Prolog:重定向系统输出

Prolog: Redirect system output

有输出错误消息的 Prolog 谓词,例如 load_files/1 以防找不到文件:

error(existence_error(source_sink,'/home/foo/nothinghere.txt'),_3724).

这些错误消息只是打印到标准输出,但不会return编辑为 prolog return 值。

在我的例子中,load_files/1 作为我不想修改的过程的一部分被深入调用。我只是提供文件名并等待 return 值。但据我了解,在这种情况下,return 值要么为 True,要么为错误。有没有什么办法可以将错误输出重定向到 return 值,这样我就可以对得到的输出做些什么?

你可以使用 catch/3.

?- catch(load_files('/tmp/exists.prolog'), E, true).
true.

?- catch(load_files('/tmp/notexists.prolog'), E, true).
E = error(existence_error(source_sink, '/tmp/notexists.prolog'), _).

catch(:Goal, +Catcher, :Recover) 用于从 :Goal.

中捕获 throw(_)
  1. Catcherthrow/1的参数统一。
  2. 使用 call/1. 调用
  3. Recover

在上面的例子中 E 结合任何错误。我们不希望这样,所以我们可以这样做:

catchFileErrors(G, F) :-
    catch(G, error(existence_error(source_sink, F), _), true).
?- catchFileErrors(load_files('exists.prolog'), E).
true.

?- catchFileErrors(load_files('notexists.prolog'), E).
E = 'notexists.prolog'.

如果您有从错误中恢复的策略,则可以将目标作为最后一个参数传递给 catch。