3

How do I write the output of listing/0 in SWI-Prolog REPL to a file ?

?- listing > file.txt.
repeat
  • 18,496
  • 4
  • 54
  • 166
sten
  • 7,028
  • 9
  • 41
  • 63

1 Answers1

8

You can open a file for writing and redirect current_ouput to it like this:

?- current_output(Orig), % save current output
   open('file.txt', write, Out),
   set_output(Out),
   listing,
   close(Out),
   set_output(Orig). % restore current output

Alternatively, SWI-Prolog provides a predicate with_output_to/2 which can be used to redirect the current output for one goal. Make sure to read the documentation, but in short:

?- open('file.txt', write, Out),
   with_output_to(Out, listing),
   close(Out).

Now the output of listing/0 will be written to file.txt. But keep in mind that there is going to be a whole lot of stuff in there. You maybe want to use listing/1 for specific predicates? In this case, using clause/2 and portray_clause/2 is another option, especially if you want more control over what and how you are writing to the file. listing is meant only for interactive use I guess.

false
  • 10,264
  • 13
  • 101
  • 209
  • 2
    Why do you say that `portray_clause/2` is preferred, when `listing(specific_pred/1)` would just do what is desired? With `portray_clause` much more has to be handled manually. – false Sep 15 '15 at 11:06
  • 1
    @false Just because of that same reason I guess. I always felt that `listing/1` is meant for using at the top level (this is how I use it at least). If one starts writing to a file, I just assume they are doing more sophisticated things than taking a look at a predicate's definition. I will correct my wording. –  Sep 15 '15 at 11:24