[Tex/LaTex] importing packages with pythontex on overleaf or journals

overleafpythontex

Alright, so I am using overleaf, and overleaf provides a simple example of pythontex which requires a latexmkrc file. So far so good. You can even open that example and start editing it. This is amazing (not sarcasm, I'm really impressed)!

If you add

\begin{pyconsole}
print("hello world")
\end{pyconsole}

to that example, it properly shows what a python session would look like.

But then, we take another step:

\begin{pyconsole}
import numpy
\end{pyconsole}

and there is an import error (yes, the resulting document actually shows a python session with an import error). So overleaf does not have numpy there by default. I can upload my own small package into my project and import it, and it works (well, except for the fact that my package relies on numpy). Uploading all of numpy into my project seems like a rabbit hole I don't want to get into [unless maybe there is a clean way to zip it and upload it…?].

I've tried creating the pythontex files on my own machine and uploading them (no good, since overleaf doesn't seem to allow that file type to be uploaded).

I tried to use pythontex to access python's os package to call pip and install numpy, but it looks like pip doesn't exist, or maybe I don't have the necessary permission to do that (os.system returned 32512). That's probably for the best – if I could use pythontex to start accessing the internet from their server's I'd probably report that to them as a possible vulnerability.

So what can I do?

Best Answer

The following steps work:

  1. Compile the latex code on my machine (and run pythontex)
  2. Then remove the python code in the .tex file. However, leave \begin{pyconsole} and \end{pyconsole} in place. [commenting it out does not work - I believe pyconsole probably redefines %]
  3. copy pythontex-files-main/main.pytxpyg to a file PythontexFile.tex.
  4. Add \input{PythontexFile} to the preamble (or I think anywhere before \begin{pyconsole})
  5. Then upload the .tex file to overleaf.

I imagine this may work with most journals.

Related Question