When working on python code in elpy, I like to have the python shell open.

Often I don't want the *Python* buffer to be visible, especially with several buffers with Python code or long Python files open.

I found the package eshell-toggle which is basically doing the same for eshell buffers what I would find useful for the *Python* buffer.

  1. If eshell-toggle’d buffer is already visible in frame for current buffer then select (toggled) eshell window.
  2. If current window is (toggled) eshell itself then hide it.

Is there a good way to toggle the *Python* buffer?

  • 1
    It seems relatively easy to write some functions that would do what you want. Leverage the functions elpy-shell-switch-to-shell and delete-window.
    – aadcg
    Commented Sep 9, 2021 at 10:40
  • How about (switch-to-buffer "*Python*")"? Or switch-to-buffer-other-window. Commented Sep 9, 2021 at 13:39

1 Answer 1


I'm not so familar with elisp, but as aadcg pointed out that elpy-shell-switch-to-shell and delete-window might work I gave it a try.

(defun python-toggle ()
  (cond ((equal (buffer-name) "*Python*") (delete-window))
        ((get-buffer "*Python*") (elpy-shell-switch-to-shell))
        ((derived-mode-p 'python-mode) (run-python))
        (t (message "Not in python-mode."))))

With this function toggling the *Python* buffer works.

If you want to bring the *Python* buffer to front when sending code via any elpy-shell-send-* function, you need to set (setq elpy-shell-display-buffer-after-send t)

But as I'm not familiar with elisp this code can probably be improved quite a bit.

  • 1
    (buffer-local-value 'major-mode (get-buffer (current-buffer))) is just major-mode. Instead of comparing strings, you can compare symbols: (eq major-mode 'python-mode). But in fact this should be (derived-mode-p 'python-mode). Commented Sep 9, 2021 at 19:26
  • @Gilles'SO-stopbeingevil' thanks for pointing that out! That's indeed better.
    – Wuff
    Commented Sep 10, 2021 at 7:17
  • 1
    @wuff nested conditionals are a bit hard to read. Consider using cond, instead of if.
    – aadcg
    Commented Sep 11, 2021 at 9:22
  • @aadcg Indeed, using cond makes it more readable! Thanks!
    – Wuff
    Commented Sep 11, 2021 at 15:52
  • I'll mark it as solved now after all your suggestions! This answer is actually more the contribution of aadcg and Gilles'SO-stopbeingevil' than mine! Thanks a lot!
    – Wuff
    Commented Sep 11, 2021 at 15:55

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.