[Tex/LaTex] Importing Python functions using pythontex

pythontex

I have a lengthy Python script (for a ML project), and I want to use some results in a LaTeX report. Using pythontex, I import my project, and it properly displays anything printed in project.py (e.g. print("Hello World") prints properly in the LaTeX pdf). However, it does not preserve variables or function definitions – so I can not use a variable defined in my project.py within a \pycode{} in my .tex file.

Any suggestions for why this is occurring, or how to get around it?

Edit – added example:

code.py

print(3)
i = 4

draft.tex

\documentclass{article}
\usepackage[margin=1.2in]{geometry}

\usepackage[gobble=auto]{pythontex}

\begin{document}
   Some text
   \begin{pycode}
      import code
      print(1)
      #print(i)
   \end{pycode}
\end{document}

When run as above, draft.pdf has Some text 3 1. If I uncomment print(i), I get an error when running pythontex.

Best Answer

OK, figured out a solution - using

from code import *

works (executes my code, and preserved variable and function definitions).

Related Question