1

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?

2
  • This would be possible, but the details would depend a lot on what you actually want to do with the text. Do you just want to capture the text verbatim and pass it to Python, or do you want TeX to do anything first? More information about exactly what you want to do would be helpful.
    – G. Poore
    Mar 12, 2016 at 18:02
  • No, the text should directly be forwarded to python, and then after returning from there tex should continue
    – arc_lupus
    Mar 12, 2016 at 18:17

1 Answer 1

3

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}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .