Running Python code in Markdown

16,278

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.

Share:
16,278
Ricardo Magalhães Cruz
Author by

Ricardo Magalhães Cruz

MS in Applied Mathematics BS in Computer Science

Updated on June 04, 2022

Comments

  • Ricardo Magalhães Cruz
    Ricardo Magalhães Cruz about 2 years

    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.)