I am using the following code snippet to write environments out to files and run arbitrary commands (like python or Rscript). It works quite nice however I would like to write something to the file before and after I insert the stuff from the enviroment there:
\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fancyvrb}
\makeatletter
\newenvironment{Rtest}[1]%
{\xdef\d@tn@me{#1}%
% \xdef\r@ncmd{Rscript #1.R > #1.Rlog}% uncomment to run command on file
\typeout{Writing file #1}\VerbatimOut{#1.R}%
}
{\endVerbatimOut %
\toks0{\immediate\write18}%
%\expandafter\toks\expandafter1\expandafter{\r@ncmd}% uncomment to run command on file
%\edef\d@r@ncmd{\the\toks0{\the\toks1}}\d@r@ncmd % uncomment to run command on file
\input{\d@tn@me.R}%
}
\makeatother
\begin{document}
\frame[containsverbatim]{
\begin{Rtest}{hello}
Hallo Welt
\end{Rtest}
}
\end{document}
What I would like to achieve is to have an environment like the following:
\begin{Rtest}{hello}{beforecode}{aftercode}
Hallo Welt
\end{Rtest}
that results in hello.R looking like this:
beforecode
Hallo Welt
aftercode
How can I modify the code above to accomplish this?


\immediate\write18{\r@ncmd}is much easier than that long series of commands:\r@ncmdhas been defined by\xdef, so it has survived full expansion so it can go as argument to\write. – egreg Dec 30 '14 at 11:01\begin{frame}[fragile]...\end{frame}and not\frame{...}. – egreg Dec 30 '14 at 11:38