Running Python and R Inside Emacs
Join the DZone community and get the full member experience.Join For Free
Emacs org-mode lets you manage blocks of source code inside a text file. You can execute these blocks and have the output display in your text file. Or you could export the file, say to HTML or PDF, and show the code and/or the results of executing the code.
Here I’ll show some of the most basic possibilities. For much more information, see orgmod.org. And for the use of org-mode in research, see A Multi-Language Computing Environment for Literate Programming and Reproducible Research.
Source code blocks go between lines of the form
On the #+begin_src line, specify the programming language. Here I’ll demonstrate Python and R, but org-mode currently supports C++, Java, Perl, etc. for a total of 35 languages.
Suppose we want to compute √42 using R.
#+begin_src R sqrt(42) #+end_src
If we put the cursor somewhere in the code block and type C-c C-c, org-mode will add these lines:
#+results: : 6.48074069840786
Now suppose we do the same with Python:
#+begin_src python from math import sqrt sqrt(42) #+end_src
This time we get disappointing results:
#+results: : None
What happened? The org-mode manual explains:
… code should be written as if it were the body of such a function. In particular, note that Python does not automatically return a value from a function unless a return statement is present, and so a ‘return’ statement will usually be required in Python.
If we change sqrt(42) to return sqrt(42) then we get the same result that we got when using R.
By default, evaluating a block of code returns a single result. If
you want to see the output as if you were interactively using Python
from the REPL, you can add :results output :session following the language name.
#+begin_src python :results output :session print "There are %d hours in a week." % (7*24) 2**10 #+end_src
This produces the lines
#+results: : There are 168 hours in a week. : 1024
Without the :session tag, the second line would not appear because there was no print statement.
I had to do a couple things before I could get the examples above to
work. First, I had to upgrade org-mode. The version of org-mode that
shipped with Emacs 23.3 was quite out of date. Second, the only language
you can run by default is Emacs Lisp. You have to turn on support for
other languages in your .emacs file. Here’s the code to turn on support for Python and R.
(org-babel-do-load-languages 'org-babel-load-languages '((python . t) (R . t)))
Opinions expressed by DZone contributors are their own.