'How do I pass a script to Sage before running it in interactive mode?

In my Python workflow, I commonly use the -i flag to open a Python interpreter which first executes the script I am working on, then allows me to interact with it. For example, in test.py:

#!/usr/bin/env python
print("Hello World")
x=2

When I run python -i test.py from the command line, I receive the following output:

Hello World!
>>> 

Interactive mode is enabled, yet all definitions made in the script are available to me. Typing x will yield 2.

Is there an analogous process for Sagemath? I have tried the -c flag, but the command sage -c "attach('test.sage')" fails to enter interactive mode after loading the module I am working on.

Ideally there would be a solution simpler that the one outlined which uses expect, but if that is indeed the best solution, how would one go about using expect to cause Sagemath to start an interactive session after loading a specific file?



Solution 1:[1]

There is a startup file you can make called init.sage for every interactive Sage session. See this FAQ and this documentation. Is that what you are looking for? You are right that sage -c only computes.

Solution 2:[2]

The Sage runtime generates for your sage script a Python script with the Sage wrapper. For example, you have script.sage.py generated from script.sage.

In the interactive mode of Sage which runs a customized IPython interpreter (see Sage Interactive shell), you can the Python script with

sage: %run script.sage.py

Solution 3:[3]

I am not sure that you can pass it before, but you can still do it within sage console.

sage: load("<path-file>")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kcrisman
Solution 2
Solution 3 jb41