9

I'm using C-c C-c to send a buffer to a Python shell. The buffer has an import at the beginning. I found that if I modify the module I'm importing, it doesn't reflect the changes if I run the buffer again with C-c C-c (it seems the Inferior Python is doing the import only once).

How can I force the Python shell to import again the modules already called in the first run of the buffer?

3 Answers 3

10

You can explicitly reload a module like so:

import mymodule
import imp
imp.reload(mymodule)
2
  • For python >= 3.1 you should use importlib instead. See here and here. Commented Jun 27, 2015 at 0:41
  • imp is deprecated since 3.4 and will be removed in 3.12, use importlib Commented Nov 27, 2023 at 23:32
5

This is my workflow. I set emacs to use ipython

(setq
 python-shell-interpreter "ipython3"
 python-shell-interpreter-args "--simple-prompt --pprint")

Then in ~/.ipython/profile_default/startup/00-ipython_init.py I put the following:

ip = get_ipython()
ip.magic('load_ext autoreload')

Then I type this whenever I modify and want to reload my modules in ipython. I like this because it works for all modules and I don't have to worry about import dependencies.

%autoreload
2

You can do it by modifying the python-run and forcing the Python process to restart:

;; Run python and pop-up its shell.
;; Kill process to solve the reload modules problem.
(defun my-python-shell-run ()
  (interactive)
  (when (get-buffer-process "*Python*")
     (set-process-query-on-exit-flag (get-buffer-process "*Python*") nil)
     (kill-process (get-buffer-process "*Python*"))
     ;; Uncomment If you want to clean the buffer too.
     ;;(kill-buffer "*Python*")
     ;; Not so fast!
     (sleep-for 0.5))
  (run-python (python-shell-parse-command) nil nil)
  (python-shell-send-buffer)
  ;; Pop new window only if shell isnt visible
  ;; in any frame.
  (unless (get-buffer-window "*Python*" t) 
    (python-shell-switch-to-shell)))

(defun my-python-shell-run-region ()
  (interactive)
  (python-shell-send-region (region-beginning) (region-end))
  (python-shell-switch-to-shell))

(eval-after-load "python"
  '(progn
     (define-key python-mode-map (kbd "C-c C-c") 'my-python-shell-run)
     (define-key python-mode-map (kbd "C-c C-r") 'my-python-shell-run-region)
     (define-key python-mode-map (kbd "C-h f") 'python-eldoc-at-point)))

http://lgmoneda.github.io/2017/02/19/emacs-python-shell-config-eng.html

1
  • Wonderful solution! You saved me few hours! Thank you! Commented Oct 22, 2018 at 21:24

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.