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
相关产品推荐
相关产品推荐

