Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Python code in Markdown

There is a lot of information on using Python code in a Markdown document. But it all seems to be about demonstrating Python snippets, not creating good looking documents.

Can I not combine Python and Markdown in a single document, like you can with R and Markdown?

MWE:

Output some text from Python in **Markdown**:
```python
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
print(clf.predict_proba(iris.data[:1, :]))
```

Compiling this: markdown_py markdown.txt

<p>Output some text from Python in <strong>Markdown</strong>:
<code>python
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
clf.predict_proba(iris.data[:1, :])</code></p>

It displays the code (cool), but does not actually run it.

Can you not run Python code in Markdown? If not, what alternatives are there?

(Using the python-markdown package from Ubuntu.)

like image 782
Ricardo Magalhães Cruz Avatar asked Oct 16 '15 08:10

Ricardo Magalhães Cruz


People also ask

Can you use Python in Markdown?

The reticulate package includes a Python engine for R Markdown that enables easy interoperability between Python and R chunks.

How do I run code in R Markdown?

You can open it here in RStudio Cloud. or by typing the chunk delimiters ```{r} and ``` . When you render your . Rmd file, R Markdown will run each code chunk and embed the results beneath the code chunk in your final report.

Is there an R Markdown equivalent in Python?

Python has the IPython notebook which is extremely like RMarkdown and it is very useful. The IPython Notebook. It works locally on your website and it is interactive just like how R works. When you are done, you can output it to html, pdf and share your analysis with others.


1 Answers

Well, I just found a solution:

Use chunks as:

<<engine='python', engine.path='python3'>>=
# python code
@
  • The engine.path by default uses the python executable, which in most Linux systems still is python2. You can ommit it if you want Python 2.
  • Do not forget to pass echo=FALSE if you want to ommit code printout, and results='asis' so that it does not try to escape the output.

You can use the following chunk at the beggining of the document to set the defaults:

<<r setup, include=FALSE>>=
knitr::opts_chunk$set(echo=FALSE, engine='whathaveyou', ...)
@

Save the file as markdown.Rmd, and use R with knitr to compile it. It will run the Python code using python.

R command: rmarkdown::render('markdown.Rmd','output.html')

Or just use RStudio.

Addendum: A native solution is apparently Pweave: it works with latex and markdown. I have not tried it yet though.

like image 53
Ricardo Magalhães Cruz Avatar answered Sep 22 '22 15:09

Ricardo Magalhães Cruz