Using python with knitr

I would like to use python along with knitr. However, python chunks are apparently evaluated separately, and variable definitions are lost between chunks.

How to solve this?

Minimal example:

test.pymd

--- title: "Minimal example" --- With a print statement. ```{r hello} x = 'Hello, Python World!' print(x) ``` Without a print statement. ```{r world} print(x) ``` 

test.md

 --- title: "Minimal example" --- With a print statement. ```python x = 'Hello, Python World!' print(x) ``` ``` Hello, Python World! ``` Without a print statement. ```python print(x) ``` ``` Traceback (most recent call last): File "<string>", line 1, in <module> NameError: name 'x' is not defined ``` 

knit2py.r

 #! /usr/bin/Rscript --vanilla args <- commandArgs(TRUE) if(length(args) < 1) { message("Need arguments in the format: %.pymd [%.md]") q(status=1) } name <- substr(args[1],1,nchar(args[1])-4) if(length(args) < 2) { args[2] <- paste0(name,".md") } library(knitr) opts_chunk$set(engine = 'python') res <- try(knit(args[1], args[2])) if(inherits(res, "try-error")) { message("Could not successfully knit RMD (or PYMD) to MD") q(status=1) } else q() 

And now run:

 ./knit2py.r test.pymd test.md 
+8
python r markdown knitr
source share
1 answer

Yes, indeed, knitr is currently not able to evaluate code stretch over several fragments for languages ​​other than R. The solution is not to use knitr, but to use pweave. The changes in the source file are minimal:

test.mdw

 --- title: "Minimal example" --- With a print statement. <<>>= x = 'Hello, Python World!' print(x) @ Without a print statement. <<>>= print(x) @ The end. 

And now run:

 pweave -f pandoc test.mdw 

There is a note on the pweave website that the installation will complete using python3. I had, however, no problem whatsoever when I just ran:

 pip install pweave pip install markdown 

Perhaps this is just an old note.

+4
source share

All Articles