Ambientes Piton e Pyluatex: grave o conteúdo em um arquivo externo

Ambientes Piton e Pyluatex: grave o conteúdo em um arquivo externo

Tenho alguns ambientes para Python criados a partir de pitonpacotes, por um lado, e Pyluatexpor outro.

Às vezes, gostaria de copiar seu conteúdo para um arquivo python externo (que será criado se ainda não existir). Você sabe como isso poderia ser feito? Por exemplo, criando um argumento opcional para os ambientes criados? Uma versão estrela de pyverbatim*, pyblock*etc?

\documentclass{article}

\usepackage{xcolor,currfile,needspace,fontawesome5,luacode}
\usepackage{pyluatex}
\usepackage{piton}

\begin{luacode}
function pytypeset()
    tex.print("\\begin{Piton}")
    tex.print(pyluatex.get_last_code())
    tex.print("\\end{Piton}")
    tex.print("")
end

function pytypesetREPL()
    tex.print("\\begin{Piton}")
    tex.print(pyluatex.get_last_output())
    tex.print("\\end{Piton}")
    tex.print("")
end
\end{luacode}

\newcommand*{\pytypeset}
    {\directlua{pytypeset()}}
\newcommand*{\pytypesetREPL}
    {\directlua{pytypesetREPL()}}

% Environnements Python
\NewPitonEnvironment{pyverbatim}{ !d<> !O{} }{
    \Needspace*{\baselineskip}
    \IfValueT{#1}{{\bfseries\sffamily\color{mongris}{\tiny\faSquare\:\faSquare\:\:}#1}}
    \PitonOptions{#2}}{}

\NewDocumentEnvironment{pyconsole}{ !d<> !O{} }
    {\Needspace*{\baselineskip}\PyLTVerbatimEnv\begin{pythonrepl}}
    {\end{pythonrepl}
    \IfValueT{#1}{{\bfseries\sffamily{\tiny\faSquare\:\faSquare\:\:}#1}}
    \PitonOptions{#2}\pytypesetREPL}
%
\newenvironment{pycode}
    {\PyLTVerbatimEnv\begin{pythonq}}
    {\end{pythonq}}
%
\NewDocumentEnvironment{pyblock}{ !d<> !O{} } 
    {\PyLTVerbatimEnv\begin{pythonq}}
    {\end{pythonq}
    \Needspace*{\baselineskip}
    \IfValueT{#1}{{\bfseries\sffamily{\tiny\faSquare\:\faSquare\:\:}#1}}
    \PitonOptions{#2}\pytypeset
    \Needspace*{\baselineskip}
    }
%
\begin{document}

\begin{pyverbatim}
x = 1   
\end{pyverbatim}

\begin{pyblock}
y = 2   
\end{pyblock}

% Desired : environments with an other option writing environment content in "filename.py"

\begin{pyverbatim}[write="filename.py"]
x = 1
\end{pyverbatim}

% at this step, the external file does not exist so the file is created and the content x=1 written to the file
\begin{pyverbatim}[write="filename.py"]
x = 1
\end{pyverbatim}

% at this step, filename.py exist, so y = 2 is added
\begin{pyblock}[write="filename.py"]
y = 2   
\end{pyblock}

\end{document}

Responder1

A versão mais recente de piton(v. 2.3 2024-01-06) fornece uma nova chave writecom essa funcionalidade.

informação relacionada