You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SWI-PROLOG中print_term无法写入文件 如何实现输出重定向

你给出的代码无法写入文件的核心原因是:SWI-Prolog的print_term/2谓词默认将输出绑定到标准输出(屏幕),不会自动继承tell/1切换后的当前输出流,因此格式化后的内容不会写入目标文件。

解决方案1:添加output参数适配tell/told逻辑

仅需要给print_term/2的第二个参数列表新增output(current_output)配置,即可让其输出到tell/1切换后的当前流,修改后代码如下:

test :-                         
  tell('junk.txt'),
  print_term(
       examples([this,is,a,really,long,example,list],
             [made,of,lists,atoms,and,including,terms(involving,parentheses,like,this)]),
       [output(current_output)]),
  told.

解决方案2:使用with_output_to自动管理流(更推荐)

使用SWI-Prolog内置的with_output_to/2谓词可以自动处理文件流的打开、关闭操作,避免手动调用tell/told遗漏导致的流泄漏问题,代码更简洁安全:

test :-
  with_output_to(file('junk.txt', [write]),
    print_term(
      examples([this,is,a,really,long,example,list],
            [made,of,lists,atoms,and,including,terms(involving,parentheses,like,this)]),
      []
    )
  ).

内容的提问来源于stack exchange,提问作者Topological Sort

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:15:08