Sorry, I should have mentioned my version info anyways. I have tested on emacs 25.3.1 and emacs 26.0.90, and org-mode versions 9.1.2 and 9.1.3 (current master).
The same error occurs on all emacs and org-mode versions. However the error slightly differs between Python and IPython interpreters. IPython prints "11" (instead of the expected "20"), whereas Python raises an IndentationError then prints "10".
I've cleaned up my patch to deal with a few edge cases. In particular:
1) Fixed a bug where I was removing blank lines (these may be needed if they are part of a multiline string object)
2) Send to tmpfile any multiline block even if not indented. This follows the python.el behavior and gives more consistent behavior for ":results output"
3) Allow ":results value" to work when the block ends in several newlines, using string-trim-right
From f009da37d3b7e2730abb8cbb10f4d07b3d456dd8 Mon Sep 17 00:00:00 2001
Date: Sun, 19 Nov 2017 07:13:56 +0000
Subject: [PATCH] Squashed commit of the following:
commit d1fe88a9f61a8e7082f08b7c190a29737bb655d5
Date: Sun Nov 19 07:08:31 2017 +0000
fix block ending in blank lines; send multiline blocks to tmpfile
commit fcc5a7795e882716775c9d925b0cd5b657da041b
Date: Sat Nov 18 22:40:31 2017 +0000
fix newlines and blanklines when sending codeblock to tmpfile
commit a5d553ece9f6ee35cd1e273e554a21a19e80ec3c
Date: Sat Nov 18 21:47:09 2017 +0000
fix newline/indentation issues in ob-python :session
---
lisp/ob-python.el | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/lisp/ob-python.el b/lisp/ob-python.el
index 60ec5fa47..c3dba1565 100644
--- a/lisp/ob-python.el
+++ b/lisp/ob-python.el
@@ -303,6 +303,9 @@ last statement in BODY, as elisp."
(mapc (lambda (line) (insert line) (funcall send-wait))
(split-string body "[\r\n]"))
(funcall send-wait)))
+ (body (if (string-match-p ".\n+." body) ;; Multiline
+ (org-babel-python--replace-body-tmpfile body)
+ body))
(results
(pcase result-type
(`output
@@ -340,6 +343,32 @@ last statement in BODY, as elisp."
(substring string 1 -1)
string))
+
+(defun org-babel-python--replace-body-tmpfile (body)
+ "Place body in tmpfile, and return string to exec the tmpfile.
+If last line of body is not indented, place it at end of exec string
+instead of tmpfile, so shell can see the result"
+ (let* ((body (string-trim-right body))
+ (tmp-file (org-babel-temp-file "python-"))
+ (lines (split-string body "[\r\n]"))
+ (lastline (car (last lines)))
+ (newbody (concat
+ (format "__pyfilename = '%s'; " tmp-file)
+ "__pyfile = open(__pyfilename); "
+ "exec(compile("
+ "__pyfile.read(), __pyfilename, 'exec'"
+ ")); "
+ "__pyfile.close()")))
+ (if (string-match-p "^[ \t]" lastline)
+ (progn
+ (with-temp-file tmp-file (insert body))
+ newbody)
+ (with-temp-file tmp-file
+ (insert (mapconcat 'identity
+ (butlast lines) "\n")))
+ (concat newbody "\n" lastline)))
+ )
+
(provide 'ob-python)
--
2.15.0