[Tex/LaTex] Latex \newcommand with python code inside

macrospackagespython

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?

Best Answer

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.