0

When I make an Org Babel shell code block with for instance a :session a header argument, it automatically makes a buffer a with the shell for this session, so I can explore it interactively.

This is a great feature. Is it possible to get the same behavior with Python blocks as well? It doesn't seem to happen automatically for me.

1 Answer 1

1

Babel evaluation of python code blocks is peculiar: using :session foo and :results output behaves most closely to what you would expect (assuming you don't expect too much...). The evaluation buffer would be *foo* in the above case (or *Python* if you don't specify a session name). See https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-python.html for some (incomplete) details, but you'll need to experiment to figure out what is going on - and be prepared for some head-scratching in the process.

But you can certainly expore it interactively. Here for example is what I get when I evaluate a python code block and then switch to the session buffer for some interactive work. First, the Org mode file:

#+begin_src python :results output :session one
  def foo(x):
    if x>0:
      return x+2
    else:
      return x-2

  print(foo(1))
  print(foo(-1))
#+end_src

Then after evaluating the block with C-c C-c, I can switch to buffer *one* where I find this (note that I use Ipython as my interactive shell because I have set python-shell-interpreter to `ipython'):

Python 3.11.6 (main, Oct  3 2023, 00:00:00) [GCC 13.2.1 20230728 (Red Hat 13.2.1-1)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.9.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 
3
-3
org_babel_python_eoe

In [6]: 

and then I can proceed to evaluate things interactively there:

Python 3.11.6 (main, Oct  3 2023, 00:00:00) [GCC 13.2.1 20230728 (Red Hat 13.2.1-1)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.9.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 
3
-3
org_babel_python_eoe

In [6]: foo
Out[6]: <function __main__.foo(x)>

In [7]: foo(5)
Out[7]: 7

In [8]: foo(-10)
Out[8]: -12

In [9]: bar
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 bar

NameError: name 'bar' is not defined

In [10]: 

The babel evaluation created the buffer, started the interpreter, evaluated the code block which defined the function foo and printed out the two numbers. The rest I typed by hand in the session buffer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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