I'm working on a package that allows Python code to be entered within certain commands and environments, saves the Python code to external files and executes it, and brings back the results via \input
. Similar to SympyTeX and SageTeX, but with additional features.
As a trivial example, \pylab{print 1+1}
would save the text string print 1+1
to a file, Python executes this file to obtain 2
and saves this in a second file, and this second file is brought back into the original document with \input
.
This is a minimal example. (It will give errors after the first run, before Python is run to create infile.tex.)
\newcommand{\pylab}[1]{
\newwrite\outputstream
\immediate\openout\outputstream=outfile.py
\immediate\write\outputstream{#1}
\immediate\closeout\outputstream
\input{infile.tex}
}
The problem is that in more complex cases, the argument for \pylab
could contain special characters, for example \pylab{print 3%2}
(modulus operator). What's the best way to deal with this? Ideally, my command would act like \verb
, so that it would take anything but * as the switch, so as to be able to work around almost any special code characters. I've been reading about verbatim, catcodes, \gdef
, etc., but I haven't been able to get anywhere with those yet.
SympyTeX and SageTeX use
\catcode`\%=12
\newcommand{\percent}{%}
\catcode`\%=14
to define a replacement for %, but I want to avoid that route if possible since it means that I can't just directly paste in valid Python code.
\newwrite\outputstream
must be outside of\pylab
and only executed once. And the percent character is already defined as\@percentchar
. – Martin Scharrer♦ May 28 '11 at 19:34