Emacs Org Mode: Running Simple Python Code

How can I execute very simple Python code in Org Emacs mode?

The first example works fine, but I can not get it to give the result of simple calculations:

; works #+begin_src python def foo(x): if x>0: return x+10 else: return x-1 return foo(50) #+end_src #+RESULTS: : 60 ; does not work #+begin_src python 1+1 #+end_src #+RESULTS: : None ; does not work #+begin_src python print(1+1) #+end_src #+RESULTS: : None 

I set the org mode using the following lines:

 ;; enable python for in-buffer evaluation (org-babel-do-load-languages 'org-babel-load-languages '((python . t))) ;; all python code be safe (defun my-org-confirm-babel-evaluate (lang body) (not (string= lang "python"))) (setq org-confirm-babel-evaluate 'my-org-confirm-babel-evaluate) 
+8
python emacs org-mode
source share
2 answers

There are two ways to get the result of the original block - output and value . You mixed them, therefore, problems.

The first block is fine.

To fix the second block:

 #+begin_src python :results value return 1+1 #+end_src 

To fix the third block:

 #+begin_src python :results output print 1+1 #+end_src 

When the output mode is value , you must return . Just put it there, as you did with 1+1 will not. In the third, you want the result to be printed, but your session defaults to the value parameter (my default values ​​are output btw).

And this bit about org-confirm-babel-evaluate has nothing to do with the question. I just set it to nil .

+13
source share

You can still run into problems, such as empty lines, causing an error in the function definition. The solution is presented in the original topic . I also posted below

 (setq org-babel-python-command "ipython3 --no-banner --classic --no-confirm-exit") ;; use %cpaste to paste code into ipython in org mode (defadvice org-babel-python-evaluate-session (around org-python-use-cpaste (session body &optional result-type result-params) activate) "Add a %cpaste and '--' to the body, so that ipython does the right thing." (setq body (concat "%cpaste\n" body "\n--")) ad-do-it (if (stringp ad-return-value) (setq ad-return-value (replace-regexp-in-string "\\(^Pasting code; enter '--' alone on the line to stop or use Ctrl-D\.[\r\n]:*\\)" "" ad-return-value)))) 
+3
source share

All Articles