Is it possible to call/reference sagetex within a latex command?

I'm doing a few projects in which it would be very helpful to get some numbers from a sagetex environment, and then directly using them within latex. I know Latex isn't great at storing numbers/information, the only way I know of to do it for now is to name and use a counter. The problem is all the commands to store data (such as /setcounter) are commands that take inputs, and I can't call sage within these commands directly. For example, I want to do the following:

    \begin{sagesilent}
a = Integer(randint(1,5))
\end{sagesilent}
\setcounter{Seed}{\sage{a}}


Unfortunately this errors out as latex can't make sense of the \sage{a} inside a command call.

Is there any way to do this, or something similar? One reason is to use sage to generate actual good random numbers for Latex to use (All the latex random number generators seem... subpar), but I have other uses I'd like, and this would make my life easier.

Here's a way. It's a bit awkward, brittle, and roundabout but it should work. The idea is to get Sage to write LateX code to a file, which you will then read into your document. Try something like this:

\begin{sagesilent}
import string
with open('counters.tex', 'w') as f:
s = string.Template(r'\setcounter{Seed}{\$seed}').substitute(seed=randint(1, 5))
f.write(s)
# more "s =" and "f.write()" as desired.
\end{sagesilent}


String formatting with { and } will drive you nuts, which is why I used Python's template strings.

After that block, counters.tex will be closed and written out to disk. Then, later in your tex file, do

\InputIfFileExists{counters.tex}


which will set the counters. (I haven't tested this, but the general idea of getting Sage/Python to write out a file -- where you can control the strings, generate the numbers, etc -- and then later just have TeX read it in -- should work.

• Turns out, 2 years later I needed to do this again and forgot I had asked (and got an answer). So after Googling my problem again, I had a laugh when I tripped across this again. Turns out, your answer is just about perfect Dan. Sage doesn't like the dot-notation in sagetex unfortunately; so it needs a slight edit if you could: \begin{sagesilent} tog = RandInt(0,1) file1 = open('counters.tex', 'w') string1 = str(r'\setcounter{Tog}{'+ str(tog) +'}') file1.write(string1) # more "string# =" and "file#.write()" as desired. \end{sagesilent} – Jason Jun 23 '18 at 22:47
• What do you mean by "Sage doesn't like the dot-notation in sagetex"? I do see that I reversed the f and open() in my with statement, and fixed that. – Dan Drake Jun 25 '18 at 13:30