A custom sweave driver
The first trick is to write a custom sweave driver, based on the basic RweaveLatex driver which does something with the content of a chunk when the engine is set to python :driver <- RweaveLatex()The only thing the driver does is convert python code chunks into a python environment, so that this in the Rnw file:
runcode <- driver$runcode
driver$runcode <- function(object, chunk, options){
if( options$engine == "python" ){
driver$writedoc( object, c("\\begin{python}", chunk, "\\end{python}") )
} else{
runcode( object, chunk, options )
}
}
Sweave( "python.Rnw", driver = driver )
<<hello,engine=python>>=becomes that in the tex file:
print "hello"
print "world"
@
\begin{python}
print "hello"
print "world"
\end{python}
Process the python code
Then you need to install the python package into your texmf tree and texhash (just google around if you don't know what it means). The python package defines the python environment so that when you compile the tex file, latex calls python and brings back the output of the python script. The catch is that you need to compile your tex file with the option
-shell-escape
. $ pdflatex -shell-escape python.tex
Beyond the simple trick
So we can get hello world from python, this needs more thinking to enable:
- production of graphics from python with a fig option, just like you do it in R, see this for example
- some way to share the data between R and python so that variables created in the R world could be used in the python world and vice-versa, I don't know the best way to do that at the moment, but from the top of my head we could either use rpy for the communication or the database that gets generated by the cacheSweave package