[Tex/LaTex] execute python code inside LaTeX

python

I come to you this time not with a bit of code but with a large question:

Is there a simple way to run some python code inside my document ?

I came across some options :

  • Sage : Quite a heavy installation… and in the end couldn't make it work.
  • An outdated file known as : python.sty, which seems to have been partially erased from the internet (many pages about it simply give a 404 error). I saw it here :https://texample.net/weblog/2008/oct/24/embedding-python-latex/ and for sure it looked promissing. It's supposed to write the code you put inside a python environnement into a file and run it, sounds too good to be true… And if it did work at some point (even in online compiling it seems), it doesn't now. I found a version of the file on an old github directory, it runs partially, but gives some compilation errors like "Missing number, treated as zero."… Some discussion suggested that it was redundant with LuaTex, I looked that up and can't really see that. It was known here too : Latex-Python combination not running on a mac
  • Right now I am having a look at Pythontex

So, any suggestion ? The best would be something I could use on Overleaf (I am allowed to dream right ?)

Why ? Because I just ended a project I wanted to do, in which my compilation does some calculations. I have met LaTeX weaknesses and limitations, and things that seem that they would be the easiest in python are really not in LaTeX.

Thank you for reading.

Best Answer

You could use pythontex or just call python by hand, here is python running on overleaf calculating 1+2=3 (there are simpler ways of adding)

enter image description here

The tex code (which needs --shell-escape but that is automatic at overleaf) is

\documentclass{article}

\begin{document}

\input{|python -c 'print(1+2)'}

\end{document}

This also works with multi-line python scripts:

enter image description here

\documentclass{article}
\usepackage{color}
\begin{document}

\input{|python mypy.py}

\end{document}

with mypy.py being

print("\\section{The First}\n")

print("Some colours:\n\n")

clr=['red','blue','green']

for c in clr:
    print("\n\\textcolor{" + c + "}{" + c +"}\n")

Example running on Overleaf (although I don't promise to keep that running forever, so here's a screenshot as well)

https://www.overleaf.com/read/gpfndyfcrhhr

enter image description here