![Piton 和 Pyluatex 环境:将内容写入外部文件](https://linux22.com/image/472520/Piton%20%E5%92%8C%20Pyluatex%20%E7%8E%AF%E5%A2%83%EF%BC%9A%E5%B0%86%E5%86%85%E5%AE%B9%E5%86%99%E5%85%A5%E5%A4%96%E9%83%A8%E6%96%87%E4%BB%B6.png)
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
。