Is it possible to create a new environment in TeX, such that the text in that environment is forwarded to a Python function with PythonTeX? It is possible to forward values to Python (by using \newenvironment{}[number]{}
, but is that also possible with the text within the second brackets? If yes, how?
1 Answer
This is a very basic solution. The text from the environment is written to a temp file, which Python then reads and passes to a function. It would be possible to avoid the temp file, but that would require a lot of LaTeX programming to capture the environment text and properly escape it so that it could be passed to Python more directly. This approach will not allow the environment to take arguments. That would make things more complicated, because then the arguments would have to be inserted into the text before it was passed to Python.
This requires the PythonTeX setting rerun=always
so that the Python code is always executed. Due to the use of the temp file, the Python code doesn't change between runs, so PythonTeX wouldn't automatically detect that code needs to be executed.
Edit: The original version used a single temp file. This wouldn't work if the environment were used multiple times. The new version uses a new temp file for each time the environment is used.
\documentclass{article}
\usepackage[rerun=always]{pythontex}
\newcounter{tempfilecounter}
\begin{pycode}
tempfile_counter = 0
def func(x):
return 'Before:\n\n' + x + '\n\nAfter'
\end{pycode}
\newenvironment{envtopyfunc}{%
\VerbatimEnvironment
\stepcounter{tempfilecounter}%
\begin{VerbatimOut}{temp\arabic{tempfilecounter}.txt}}%
{\end{VerbatimOut}%
\pyc{tempfile_counter += 1}%
\pyc{f=open('temp{0}.txt'.format(tempfile_counter)); print(func(f.read())); f.close()}}
\begin{document}
\begin{envtopyfunc}
Line 1 ...
Line 2 ...
\end{envtopyfunc}
\end{document}
python
, and then after returning from theretex
should continue