Piton 和 Pyluatex 环境:将内容写入外部文件

Piton 和 Pyluatex 环境:将内容写入外部文件

piton一方面,我有几个由包创建的 Python 环境,Pyluatex另一方面。

有时我想将它们的内容复制到外部 Python 文件中(如果该文件不存在,则创建该文件)。你知道怎么做吗?例如,通过为创建的环境创建一个可选参数?等等的星号pyverbatim*版本pyblock*

\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}

答案1

最新版本piton(v. 2.3 2024-01-06)提供了具有该功能的新密钥write

相关内容