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 ofpython
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:
Then, the contents of the environment
python0
will be written to the filecomment.cut
, the file will be executed by python, with any output written tocomment.out
and any errors written tocomment.err
. Like with thepython
package, you have to usepdflatex
with the option--shell-escape
.Your sample code:
The typeset document will look like
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 thepython
environment for including the output of the program and thepython0
environment for not including it.