Sign up ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I have used the python package to include Python in my LaTeX document which works fine.

I am trying to access the Python variables/calculations outside of \begin{python} ... \end{python}, without luck.

My question is: Can I? or How do I access variables/calculations within Python code embedded in LaTeX?

Simple example

tdegc = 25.0
tdegf = (tdegc - 32.0)/1.0
print 'T in DegC is ', tdegc , ' in Deg F is ', tdegf

My calculations show that $\mbox{tdegf} = $ tdegf (this is the value for tdegf)

share|improve this question
My experience with this python.sty is limited, but I thought it was only for producing output - it doesn't modify the tex environment outside of the python environment, so there's no way to access these variables. – Thomas Oct 30 '11 at 15:48
I am not 100% clear on your intent. Are you interested in using (say) \tdegf in your main document (outside \begin{python}...\end{python}) and it should print the equivalent of \tdegc in Fahrenheit? As in -3.889? By the way, your Fahrenheit calculation is incorrect: tdegf = (tdegc - 32.0)*(5/9). – Werner Oct 30 '11 at 15:51
I don't see the reason why the author of the package must be mentioned this explicitly. A link to the package would be much better. I only found a dangling link to the authors former University page. – Martin Scharrer Oct 30 '11 at 15:56
Oops - I meant "1.8" (and thanks) - I see what the problem is - the python.sty file is just a way to embed python and not access tex variables – Krishnan Oct 30 '11 at 16:50
It is not a way to embed Python, only a way to lay out Python source code within a LaTeX document. – reinierpost Jan 30 '12 at 13:09

5 Answers 5

I've played around a little with the sagetex package (designing tests which can be randomized) and I think you should look into its documentation. sagetex allows you incorporate Sage into your LaTeX code. Since Sage is based Python, you can run Python using sagetex. There is a \sage command that lets you jump back in to work with variables you've defined before, which I think is the issue you are concerned about. You can find some examples on CTAN. Here's a cut down sample:


\begin{sagesilent}%use sage without producing output
n, x = var('n x')
a = ZZ.random_element(-10,10)
while a == 0:
   a = ZZ.random_element(-10,10)
b = ZZ.random_element(-10,10)
c = ZZ.random_element(-10,10)
d = ZZ.random_element(2,9)
ratexp1 = (a*n)/(a*n+1)
ratexp2 = (d**(d*n-1))/((d+1)**n)
ratexp3 = 1/(a*x+b)
deriv1 = diff(ratexp3,x,1)
\begin{enumerate} %creates the numbering for the problems.
\item $\Sigma_{n=1}^{\infty} \sage{ratexp2}$

\vskip 2 in %leaves 2 inches of space for student work
\item Find the derivative of $\sage{ratexp3}$. The answer is $\sage{deriv1}$

\vskip 2 in %leaves 2 inches of space for student work
\item Consider the series: $ \Sigma_{n=1}^{\infty}\sage{ratexp1} $
Find a formula for $s_n$, the nth partial sum. 

The code is choosing random elements for a,b,c,d but throws out a if a=0. I then defined rational expressions (to be used in the problems) and even calculated a derivative. At that point, I left Sage but I can still access the past work (even in math mode) using the \sage command; eg. \sage{ratexp2}.

Note: although I used a = ZZ.random_element(-10,10) to produce random integers, you can use the typical Python commands to produce random numbers. You'll also need to install Sage, along with the style file. Just like the python package, compiling the code produces an intermediate file (.sage file) which you process with Sage. sagetex is a very powerful package.

share|improve this answer
I will try embedding python into \begin{sagetex} and try to access the variables that way - that may be the solution indeed ... thanks – Krishnan Oct 30 '11 at 17:20
@DJP I was wondering if you know if it is possible to use these variable, say your "a" as an argument of a LaTeX command. For example, I tried using a \foreach \n in {1,...,\sage{n}}{whatever here} where n was previously assigned a value in a sageblock environment, but it would not compile. I'm thinking it is because the way \sage return it's value is different than rather typing a fixed number – Jean-Sébastien Feb 7 '14 at 7:50
There's some mixing of the Sage and LaTeX variables ( page 5-6 of the documentation link) but not (that I know of) in the way you're asking. Generally, you'd have the \foreach structure coded within the Sage block as a for loop in Python which would then get inserted as a string. Look at my answer for the Weierstrass function: Sage calculate the points which are then inserted into a LaTeX statement within the sagesilent block: output += r"\draw[blue, thin]...and then put into Latex with the \sagestr command – DJP Feb 7 '14 at 22:51
I'll have a look thanks – Jean-Sébastien Feb 8 '14 at 15:57
My last comment was partially wrong (no Python for loop needed). Inside a sagesilent block there would be something like: output += r"\foreach \n in {1,...,%d}{whatever here}"%(n) where n was the variable. There are various issues that can arise depending on the specifics of "whatever here"; eg, Sage integers and Python Integers are different. It's difficult to say for sure without knowing the specific problem. – DJP Feb 8 '14 at 17:48

There is also SympyTeX, a package that allows you to use the complete functionality of python and sympy within your LaTeX document.

Here is an example: Using sympy within your LaTeX document is as easy as $2+2=\sympy{2+2}$.

You can write a block, and then use the variables defined later in your code!
    x = sympy.Symbol('x')
    h = sympy.integrate(1+x,x)
The variable $h$, how can be called using {\verb \sympy{h} }, and you will get $h =  
\sympy{h}$. Similarly, the integral of $1+x^4$ is $\sympy{sympy.integrate(1+x**4,x)}$.

This will result in: enter image description here

As far as I know it is not yet available on CTAN but you can download it from the author's homepage: SympyTeX

share|improve this answer

This is too long to be a comment, since the OP's intent is not 100% clear.

There is usually very little in terms of interaction between environments used and whatever is contained within them that can be used outside of that environment. Typically, environments are used to format its contents in a general way, performing certain operations at the start of the environment (at \begin{<env>}) and some at the end (at \end{<env>}).

If you're interested in performing calculations within your document, or at least mimic it without going through the trouble of specifying things verbatim, the fp package provides floating point operations at compile time. Here is a short example:

enter image description here

\newcommand{\degrees}[1][C]{{}^\circ\mathrm{#1}}% degrees celcius/fahrenheit
% Celcius <-> Fahrenheit conversions:
Some temperature conversions:
  \item \FPeval{\result}{round((89.2-32)*(5/9),1)}%
  \item \FPeval{\result}{round(25*(9/5)+32,1)}%

As a result, it is now possible to include python code in your document and you could use inline fp code (outside the python environment) to calculate expressions that you can typeset in your document.

share|improve this answer
I am familiar with the fp package, it is very nice and useful and do use it often ... with python, there are other things I can do (!) – Krishnan Oct 30 '11 at 17:19
@Krishnan: Sure. The python package and similarly-named python environment doesn't allow you to do that. @DJP's answer does something similar to what you're after, only for Sage. – Werner Oct 30 '11 at 17:21
Another option is to use luatex to get acess to a proper programming language within TeX. – Aditya Oct 30 '11 at 17:56

Look for the pythontex package on CTAN or gitHub. It lets you embed python code (including sympy and pyplot code) in your LaTeX document and access the results for typesetting. You can directly access variable values or have a Python print statement generate LaTeX commands. It handles individual statements (\py{math.cos(3.14159/4)} or \py{"The square root of 2. is {0:3g}".format(math.sqrt(2.))} or whole blocks of code. It will also allow code to be typeset with or without execution.

share|improve this answer

You can also use Pweave, which unlike pythontex only needs to run once.

Here is a more complex example that includes localisation.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.