It would be great if we could not only use R or S in sweave code chunks but also some other languages such as python for example. Why would you want that, well python has some additional graphics capabilities R does not have, some software is written in python but you still want to write your document in sweave, ... Here is a first attempt, obviously not complete.

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() 
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 )
The only thing the driver does is convert python code chunks into a python environment, so that this in the Rnw file:
<<hello,engine=python>>=
print "hello"
print "world"
@
becomes that in the tex file:
\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