## PythonTeX Gallery

July 3, 2020

Abstract

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
»> âæéöø + ßçñðŠ
579

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
468
»> def f(expr):
...     return(expr**4)
...
»> f(x)
228886641
»> 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)
 $\int \left({x}^{3}+{\mathrm{cos}}^{5}\left(x\right)\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}=\frac{{x}^{4}}{4}+\frac{{\mathrm{sin}}^{5}\left(x\right)}{5}-\frac{2{\mathrm{sin}}^{3}\left(x\right)}{3}+\mathrm{sin}\left(x\right)$

It’s easy to use arbitrary symbols in equations.

phi = Symbol(r'\phi')= Integral(exp(-phi**2), (phi, 0, oo))
 $\underset{0}{\overset{\infty }{\int }}{e}^{-{\varphi }^{2}}\phantom{\rule{0.3em}{0ex}}\mathit{d\varphi }=\frac{\sqrt{\pi }}{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)
figure(figsize=(42.5))
plot(x, sin(x), label='$\sin(x)$')
xlabel(r'$x\mathrm{-axis}$')
ylabel(r'$y\mathrm{-axis}$')
legend(loc='lower right')
savefig('myplot.pdf', bbox_inches='tight')

### 6 Basic pylab interaction

 ${\int }_{0}^{\infty }{e}^{-{x}^{2}}\phantom{\rule{0.3em}{0ex}}\mathit{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
3var('x')
4
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)']
10
11print(r'\begin{align*}')
12
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)) + '&=' +
21    print(latex(eval(myint)) + '&=' +
22            latex(eval(myint+'.doit()')) + r'\\')
23print(r'\end{align*}')

$\begin{array}{llllllll}\hfill \frac{d}{\mathit{dx}}\mathrm{sin}\left(x\right)& =\mathrm{cos}\left(x\right)\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{sin}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =-\mathrm{cos}\left(x\right)\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}\mathrm{cos}\left(x\right)& =-\mathrm{sin}\left(x\right)\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{cos}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =\mathrm{sin}\left(x\right)\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}\mathrm{tan}\left(x\right)& ={\mathrm{tan}}^{2}\left(x\right)+1\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{tan}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =-\mathrm{log}\left(\mathrm{cos}\left(x\right)\right)\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}{\mathrm{sin}}^{2}\left(x\right)& =2\mathrm{sin}\left(x\right)\mathrm{cos}\left(x\right)\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int {\mathrm{sin}}^{2}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =\frac{x}{2}-\frac{\mathrm{sin}\left(x\right)\mathrm{cos}\left(x\right)}{2}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}{\mathrm{cos}}^{2}\left(x\right)& =-2\mathrm{sin}\left(x\right)\mathrm{cos}\left(x\right)\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int {\mathrm{cos}}^{2}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =\frac{x}{2}+\frac{\mathrm{sin}\left(x\right)\mathrm{cos}\left(x\right)}{2}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}{\mathrm{tan}}^{2}\left(x\right)& =\left(2{\mathrm{tan}}^{2}\left(x\right)+2\right)\mathrm{tan}\left(x\right)\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int {\mathrm{tan}}^{2}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =-x+\frac{\mathrm{sin}\left(x\right)}{\mathrm{cos}\left(x\right)}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}\mathrm{asin}\left(x\right)& =\frac{1}{\sqrt{1-{x}^{2}}}\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{asin}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =x\mathrm{asin}\left(x\right)+\sqrt{1-{x}^{2}}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}\mathrm{acos}\left(x\right)& =-\frac{1}{\sqrt{1-{x}^{2}}}\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{acos}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =x\mathrm{acos}\left(x\right)-\sqrt{1-{x}^{2}}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}\mathrm{atan}\left(x\right)& =\frac{1}{{x}^{2}+1}\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{atan}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =x\mathrm{atan}\left(x\right)-\frac{\mathrm{log}\left({x}^{2}+1\right)}{2}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}\mathrm{sinh}\left(x\right)& =\mathrm{cosh}\left(x\right)\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{sinh}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =\mathrm{cosh}\left(x\right)\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}\mathrm{cosh}\left(x\right)& =\mathrm{sinh}\left(x\right)\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{cosh}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =\mathrm{sinh}\left(x\right)\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill \frac{d}{\mathit{dx}}\mathrm{tanh}\left(x\right)& =1-{\mathrm{tanh}}^{2}\left(x\right)\phantom{\rule{1em}{0ex}}\phantom{\rule{2em}{0ex}}& \hfill \phantom{\rule{1em}{0ex}}\int \mathrm{tanh}\left(x\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}& =x-\mathrm{log}\left(\mathrm{tanh}\left(x\right)+1\right)\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill & \phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}& \hfill \end{array}$

### 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)')
3
4# Define limits of integration
5x_llim = 0
6x_ulim = 2
7y_llim = 0
8y_ulim = 3
9z_llim = 0
10z_ulim = 4
11
12print(r'\begin{align*}')
13
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'\\')
19
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'\\')
25
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'\\')
29
30right = Integral(f, (z, z_llim, z_ulim), (y, y_llim, y_ulim),
31                 (x, x_llim, x_ulim)).doit()
32print('&=' + latex(right) + r'\\')
33
34print('&=' + latex(N(right)) + r'\\')
35
36print(r'\end{align*}')

$\begin{array}{llll}\hfill \underset{0}{\overset{4}{\int }}\underset{0}{\overset{3}{\int }}\underset{0}{\overset{2}{\int }}f\left(x,y,z\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}\phantom{\rule{0.3em}{0ex}}\mathit{dy}\phantom{\rule{0.3em}{0ex}}\mathit{dz}& =\underset{0}{\overset{4}{\int }}\underset{0}{\overset{3}{\int }}\underset{0}{\overset{2}{\int }}\left(\mathit{xy}+y\mathrm{sin}\left(z\right)+\mathrm{cos}\left(x+y\right)\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}\phantom{\rule{0.3em}{0ex}}\mathit{dy}\phantom{\rule{0.3em}{0ex}}\mathit{dz}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill & =\underset{0}{\overset{3}{\int }}\underset{0}{\overset{2}{\int }}\left(4\mathit{xy}-y\mathrm{cos}\left(4\right)+y+4\mathrm{cos}\left(x+y\right)\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}\phantom{\rule{0.3em}{0ex}}\mathit{dy}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill & =\underset{0}{\overset{2}{\int }}\left(18x-4\mathrm{sin}\left(x\right)+4\mathrm{sin}\left(x+3\right)-\frac{9\mathrm{cos}\left(4\right)}{2}+\frac{9}{2}\right)\phantom{\rule{0.3em}{0ex}}\mathit{dx}\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill & =4\mathrm{cos}\left(3\right)+4\mathrm{cos}\left(2\right)-4\mathrm{cos}\left(5\right)-9\mathrm{cos}\left(4\right)+41\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill & =40.1235865133293\phantom{\rule{2em}{0ex}}& \hfill & \phantom{\rule{2em}{0ex}}\\ \hfill & \phantom{\rule{2em}{0ex}}& \hfill \end{array}$

### 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 "py_errorsession_9.py", 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.