Remove line break introduced by python environment

environmentspython

Suppose in my LaTeX file I need to create a python environment to execute some python code which does not create any LaTeX code. The python environment would still create a (blank) minipage which causes a vertical space. Is there a LaTeX way to compile the python environment and have the minipage removed?

For instance suppose I have this LaTeX fragment:

Before 
\begin{python}
f = open('abc.txt', 'w')
f.write('hello')
f.close()
\end{python}
After

I would like to have this in the pdf generated by pdflatex:

Before After

and the python code in the python environment executed.

Here's a min working example:

\documentclass{article}
\usepackage{python}
\begin{document}

Before
\begin{python}
f = open('a.txt', 'w')
f.write("hello")
f.close()
\end{python}
After

\end{document}

Compile above with

pdflatex --shell-escape main.tex

Best Answer

Here is another solution using the comment package instead of python that does not have the problem with extra newlines and spaces. This solution only executes the Python script, but does not include its output.

Add the following lines to your preamble:

\usepackage{comment}
\specialcomment{python0}{%
  \begingroup
  \def\ProcessCutFile{}%
}{%
  \immediate\write18{python comment.cut > comment.out 2> comment.err}%
  \endgroup
}

Then, the contents of the environment python0 will be written to the file comment.cut, the file will be executed by python, with any output written to comment.out and any errors written to comment.err. Like with the python package, you have to use pdflatex with the option --shell-escape.

Your sample code:

\documentclass{article}
\usepackage{comment}
\specialcomment{python0}{%
  \begingroup
  \def\ProcessCutFile{}%
}{%
  \immediate\write18{python comment.cut > comment.out 2> comment.err}%
  \endgroup
}
\begin{document}
Before
\begin{python0}
f = open('a.txt', 'w')
f.write("hello")
f.close()
\end{python0}
After
\end{document}

The typeset document will look like

Before After

where the space between the two words originates from the space/newline after Before in the source code (add % after Before to avoid it).

You can use this solution together with the python package, then you have the python environment for including the output of the program and the python0 environment for not including it.

Related Question