0

Consider a block of python code in an org-mode document:

#+begin_src python

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result)

#+end_src

If I were to open a similar block of Rcode in org-edit-special I could use ess-eval-line to run this line-by-line or ess-eval-region to run a highlighted region.

How can I get similar functionality for blocks of code, written in python?

  • 1
    Maybe edit the question? For now setting :results output and M-x org-babel-execute-src-block RET will do it. – Andreas Röhler Aug 11 at 6:06
1

From within org-edit-special, I found that you can evaluate a highlighted region by running python-shell-send-region (which should default to C-c C-r). As for evaluating an single line, I wrote my own function, python-shell-send-line, which I load from init.el:

;; Add a function to send a single line to the Python console
(defun python-shell-send-line ()
  (interactive)
  (save-mark-and-excursion
    (move-beginning-of-line nil)
    (set-mark-command nil)
    (move-end-of-line nil)
    (python-shell-send-region
     (region-beginning)
     (region-end))))

;; Create shortcut
(with-eval-after-load "python" (define-key python-mode-map
                 (kbd "C-c C-j")
                 'python-shell-send-line))
  • What is wrong with Andreas Röhler's suggestion of adding :results output and pressing C-c C-c? – NickD Aug 11 at 21:00
  • Unless I am mistaken, that would evaluate the entire block. I was looking for a way to evaluate a single line of code and also a marked region. – Adam Aug 12 at 2:14
  • OK - I see. I didn't read the question carefully enough. – NickD Aug 12 at 3:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.