1 | initial version |
Hello, @cybervigilante! I believe I have a solution for your problem. Let me say this was extremely difficult, and it is a little "hacky", but it should work just fine. I say "hacky" because I am going to exploit the very same fact that is causing you trouble: Jupyter notebooks don't show the output of print()
functions from the file init.sage
.
Sage notebooks use the custom SageKernel
kernel class to run. This just inherits from the IPythonKernel
class, and makes some customizations. One of these customizations is the banner that is displayed at startup. We are going to add some text to that banner. Here is some the example I will use:
from sage.repl.ipython_kernel.kernel import SageKernel
from sage.misc.banner import banner_text
%colors Linux
f(x) = 2*x^2
def my_banner(show_banner=False):
if show_banner:
text = [banner_text()]
else:
text = []
text.append(str(f))
text.append('Ctrl+D ends the session')
return '\n'.join(text)
print(my_banner())
SageKernel.banner = my_banner(True)
Let me explain what this all means. First, we import the SageKernel
class, which will be automatically used when you run Jupter(lab), and also the banner_text()
function, which creates the nice SageMath banner. The line %colors Linux
is there as it seems to be a popular choice for Sage Shell colors, but also in order to show that this solution does not interfere with other user code in init.sage
. Then, I defined a function f
to serve as an example of some user-defined content that can be displayed with this solution.
The important part is the my_banner()
function. It creates a list of text (creatively called text
in the code) that you want to print. All you need to do is append
to that variable text
. In the code, I appended as string representation of my function f
and some line to remember the Crtl+D
shortcut. The function will concatenate everything you put in text
, with every entry separated with a new line character (that's the part \n.join(text)
.)
Then comes the complicated part part. When you start a terminal session of Sage, the banner seems to come from some other part (which I couldn't determine conclusively.) That is why I printed the output of my_banner()
using the default value of show_banner=False
; otherwise, we'd get the banner twice. On the other hand, when you run a notebook, the banner comes from SageKernel.banner
, so I assigned it the output of my_banner()
with show_banner
set to True
; otherwise, the banner won't show up because we are overwriting it.
This brings me to the "hacky part": the print(my_banner())
line is executed when you use a terminal, but the SageKernel.banner = my_banner(True)
line has no effect in that case; all the way around, the former has no effect for notebooks, while the latter shows output.
I hope this helps!