PythonTeX Gallery

Geoffrey M. Poore

July 3, 2020


PythonTeX allows you to run Python code from within LaTeX documents and automatically include the output. This document serves as an example of what is possible with PythonTeX.

1 General Python interaction

We can typeset code that is passed to Python, and bring back the results.

This can be simple. For example, print('Python says hi!') returns the following:

Python says hi!

Or we could access the printed content verbatim (it might contain special characters):

Python says hi!

Python interaction can also be more complex. print(str(2**2**2+ r'\endinput') returns 16. In this case, the printed result includes LaTeX code, which is correctly interpreted by LaTeX to ensure that there is not an extra space after the 16. Printed output is saved to a file and brought back in via \input, and the \endinput command stops input immediately, before LaTeX gets to the end of the line and inserts a space character there, after the 16.

Printing works, but as the last example demonstrates, you have to be careful about spacing if you have text immediately after the printed content. In that case, it’s usually best to assemble text within a PythonTeX environment and store the text in a variable. Then you can bring in the text later, using the \py command. The \py command brings in a string representation of its argument. First we create the text.

mytext = '$1 + 1 = {0}$'.format(1 + 1)

Then we bring it in: 1 + 1 = 2. The \py command can even bring in verbatim content.

We don’t have to typeset the code we’re executing. It can be hidden. And then we can access it later: This is a message from Python.

It is also possible to perform variable substitution or string interpolation. The earlier result could be recreated: 1 + 1 = 2.

2 Pygments highlighting

PythonTeX supports syntax highlighting via Pygments. Any language supported by Pygments can be highlighted. Unicode is supported. Consider this snippet copied and pasted from a Python 3 interactive session. (Using random strings of Unicode for variable names is probably not a good idea, but PythonTeX will happily highlight it for you.)

»> âæéöø = 123»> ßçñðŠ = 456
»> âæéöø + ßçñðŠ

There is also a Pygments command for inline use: \pygment.

3 Python console environment

PythonTeX includes an environment that emulates a Python interactive session. Commands are entered within the environment, each line is treated as input to an interactive session, and the result is typeset.

»> = 123»> = 345
»> = x + y
»> z
»> def f(expr):
...     return(expr**4)
»> f(x)
»> print('Python says hi from the console!')
Python says hi from the console!

It is possible to refer to the values of console variables later on in inline contexts, using the \pycon command. For example, the value of z was 468.

4 Basic SymPy interaction

PythonTeX allows us to perform algebraic manipulations with SymPy and then properly typeset the results.

We create three variables, and define z in terms of the other two.

var('x, y, z')= x + y

Now we can access what z is equal to:

z = x + y

Many things are possible, including some very nice calculus.

= x**3 + cos(x)**5= Integral(f, x)
x3 + cos 5xdx = x4 4 + sin 5x 5 2sin 3x 3 + sin x

It’s easy to use arbitrary symbols in equations.

phi = Symbol(r'\phi')= Integral(exp(-phi**2), (phi, 0, oo))
0eϕ2 = π 2

5 Plots with matplotlib

We can create plots with matplotlib, perfectly matching the plot fonts with the document fonts. No more searching for the code that created a figure!

It is possible to pass page dimensions and similar contextual information from the LaTeX side to the Python side. If you want your figures to be, for example, a particular fraction of the page width, you can pass the value of \textwidth to the Python side, and use it in creating your figures. See \setpythontexcontext in the main documentation for details.

You may want to use matplotlib’s PGF backend when creating plots.

rc('text', usetex=True)rc('font', family='serif')
rc('font', size=10.0)
rc('legend', fontsize=10.0)
rc('font', weight='normal')
= linspace(010)
plot(x, sin(x), label='$\sin(x)$')
legend(loc='lower right')
savefig('myplot.pdf', bbox_inches='tight')


6 Basic pylab interaction

from scipy.integrate import quadmyintegral = quad(lambda x: e**-x**20, inf)[0]
0ex2 dx = 0.886226925452758

7 An automated derivative and integral table

PythonTeX allows some amazing document automation, such as this derivative and integral table. Try typing that by hand, fast!

1from re import sub 2
5# Create a list of functions to include in the table
6funcs = ['sin(x)''cos(x)''tan(x)',
7         'sin(x)**2''cos(x)**2''tan(x)**2',
8         'asin(x)''acos(x)''atan(x)',
9         'sinh(x)''cosh(x)''tanh(x)']
13for func in funcs:
14    # Put in some vertical space when switching to arc and hyperbolic funcs
15    if func == 'asin(x)' or func == 'sinh(x)':
16        print(r'&\\')
17    myderiv = 'Derivative(' + func + ', x)'
18    myint = 'Integral(' + func + ', x)'
19    print(latex(eval(myderiv)) + '&=' +
20            latex(eval(myderiv + '.doit()')) + r'\quad & \quad')
21    print(latex(eval(myint)) + '&=' +
22            latex(eval(myint+'.doit()')) + r'\\')

d dxsin x = cos x sin xdx = cos x d dxcos x = sin x cos xdx = sin x d dxtan x = tan 2x + 1 tan xdx = log cos x d dxsin 2x = 2sin xcos x sin 2xdx = x 2 sin xcos x 2 d dxcos 2x = 2sin xcos x cos 2xdx = x 2 + sin xcos x 2 d dxtan 2x = 2tan 2x + 2tan x tan 2xdx = x + sin x cos x d dxasin x = 1 1 x2 asin xdx = xasin x + 1 x2 d dxacos x = 1 1 x2 acos xdx = xacos x 1 x2 d dxatan x = 1 x2 + 1 atan xdx = xatan x log x2 + 1 2 d dxsinh x = cosh x sinh xdx = cosh x d dxcosh x = sinh x cosh xdx = sinh x d dxtanh x = 1 tanh 2x tanh xdx = x log tanh x + 1

8 Step-by-step solutions

Using SymPy, it is possible to typeset step-by-step solutions. In this particular case, we also use the mdframed package to place a colored background behind our code.

Step-by-Step Integral Evaluation

1x, y, z = symbols('x,y,z')2f = Symbol('f(x,y,z)')
4# Define limits of integration
5x_llim = 0
6x_ulim = 2
7y_llim = 0
8y_ulim = 3
9z_llim = 0
10z_ulim = 4
14# Notice how I define f as a symbol, then later as an actual function
15left = Integral(f, (x, x_llim, x_ulim), (y, y_llim, y_ulim), (z, z_llim, z_ulim))
16f = x*+ y*sin(z) + cos(x+y)
17right = Integral(f, (x, x_llim, x_ulim), (y, y_llim, y_ulim), (z, z_llim, z_ulim))
18print(latex(left) + '&=' + latex(right) + r'\\')
20# For each step, I move limits from an outer integral to an inner, evaluated
21# integral until the outer integral is no longer needed
22right = Integral(Integral(f, (z, z_llim, z_ulim)).doit(), (x, x_llim, x_ulim),
23                 (y, y_llim, y_ulim))
24print('&=' + latex(right) + r'\\')
26right = Integral(Integral(f, (z, z_llim, z_ulim), (y, y_llim, y_ulim)).doit(),
27                 (x, x_llim, x_ulim))
28print('&=' + latex(right) + r'\\')
30right = Integral(f, (z, z_llim, z_ulim), (y, y_llim, y_ulim),
31                 (x, x_llim, x_ulim)).doit()
32print('&=' + latex(right) + r'\\')
34print('&=' + latex(N(right)) + r'\\')

040302f(x,y,z)dxdydz =040302 xy + ysin z + cos x + ydxdydz =0302 4xy ycos 4 + y + 4cos x + ydxdy =02 18x 4sin x + 4sin x + 3 9cos 4 2 + 9 2dx = 4cos 3 + 4cos 2 4cos 5 9cos 4 + 41 = 40.1235865133293

9 Including stderr

PythonTeX allows code to be typset next to the stderr it produces. This requires the package option makestderr.

1x = 1232y = 345
3z = x + y +

This code causes a syntax error:

  File "", line 3     z = x + y +
SyntaxError: invalid syntax

The package option stderrfilename allows the file name that appears in the error message to be customized.

Since PythonTeX runs Python code (and potentially other code) on your computer, documents using PythonTeX have a greater potential for security risks than do standard LaTeX documents. You should only compile PythonTeX documents from sources you trust.