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

相關內容