# Latex \newcommand with python code inside

I'm extremely new to Latex. I'm using python package to insert graphics in a loop. What I can not understand is how I can transform this code

\documentclass{article}
\usepackage{python}

\begin{document}

\begin{figure}
\centering
\begin{python}
import os
print r"\fbox{bla bla}"
\end{python}
\end{figure}

\end{document}


into something like

\documentclass{article}
\usepackage{python}

\newcommand\insPython[1]{
{
\begin{figure}
\centering
\begin{python}
import os
print r"#1"
\end{python}
\end{figure}
}

\begin{document}

\insPython{bla bla}

\end{document}


The second version does not work. Is there any way to wrap a Python code into a Latex command?

One way would be to use pythontex package:

\documentclass{article}
\usepackage{pythontex}

\newcommand\insPython[1]{
\begin{figure}
\centering
\pyc{import os;
print (r"#1")}
\end{figure}
}

\begin{document}
\insPython{bla bla}

\end{document}


You need to run pdflatex then pythontex (or pythontex.exe) and pdflatex again.

Somehow I needed to use Python 3 syntax, but maybe because I have both Python 2 and Python 3 installed on my system.

• Regarding Python 3 syntax: pythontex imports everything from __future__ except for unicode_literals by default. This can be modified using the pyfuture package option. – G. Poore Apr 7 '14 at 23:22
• @Tahtisilma, thank you a lot! Your solution worked fine for me. – Vladimir Ivannikov Apr 8 '14 at 10:29