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?

  • 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 '16 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 '16 at 18:17

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.




tempfile_counter = 0
def func(x):
    return 'Before:\n\n' + x + '\n\nAfter' 

  \pyc{tempfile_counter += 1}%
  \pyc{f=open('temp{0}.txt'.format(tempfile_counter)); print(func(f.read())); f.close()}}


Line 1 ...

Line 2 ...

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.