Using python together with knitr : <p>I would like to use python together with knitr.  However, python chunks seem to get evaluated separately, and variable definitions are lost between chunks.</p>

<p>How to solve this? </p>

<p>Minimal example:</p>

<h3>test.pymd</h3>

<pre><code>---
title: "Minimal example"
---

With a print statement.

```{r hello}
x = 'Hello, Python World!'
print(x)
```

Without a print statement.

```{r world}
print(x)
```
</code></pre>

<h3>test.md</h3>

<pre><code>---
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 "&lt;string&gt;", line 1, in &lt;module&gt;
NameError: name 'x' is not defined
```
</code></pre>

<h3>knit2py.r</h3>

<pre><code>#! /usr/bin/Rscript --vanilla

args &lt;- commandArgs(TRUE)

if(length(args) &lt; 1) {
    message("Need arguments in the format: %.pymd [%.md]")
    q(status=1)
}

name &lt;- substr(args[1],1,nchar(args[1])-4)

if(length(args) &lt; 2) {
    args[2] &lt;- paste0(name,".md")
}

library(knitr)
opts_chunk$set(engine = 'python')

res &lt;- 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()
</code></pre>

<p>And now run:</p>

<pre><code>./knit2py.r test.pymd test.md 
</code></pre>
