REPL-like output
Hello, Sage Community.
If I run the sage REPL in a terminal, and execute something like
for i in range(4):
print(i^2)
then we all know that Sage prints
0
1
4
9
In this case, I could create a class to intercept standard output to a variable, like:
class verboseBuffer:
def __init__(self):
self.buffer = ''
def write(self, s):
self.buffer += s
Then I just make
_verbOut_ = verboseBuffer()
sys.stdout = _verbOut_
and if I run the first chunk of code, then the integers will be stored in _verbOut_.buffer
, instead of being printed to standard output as before. I finally can do
sys.stdout = sys.__stdout__
print(_verbOut_.buffer)
and this prints the contents of _verbOut_.buffer
, i.e., the list at the beginning.
Now consider the same loop without the print
:
for i in range(4):
i^2
Executed in the REPL, Sage will print exactly the same as before (even if I haven't specified to print
), and I could do the same thing to redirect the standard output to a variable.
Now, on the other hand, I have a huge file for which I would like to print everything in the same way it is printed in the REPL. I can't add print
to every single part of the file, so I have tried to redirect output to a variable as before, and print it in the last line. The problem is that, things like the last chunk of code, without an explicit print
won't be stored in _verbOut_.buffer
at the end of the execution.
My questions are:
- Why does the Sage REPL prints all computations not assigned to a variable, like the
i^2
in the loop, but that doesn't happen if the code is in a file? - How can I obtain a REPL-like output without having to add
print
to everything in my long file?