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?

9

You can explicitly reload a module like so:

import mymodule
import imp
imp.reload(mymodule)
4

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
1

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

  • Wonderful solution! You saved me few hours! Thank you! – DmitrySemenov Oct 22 '18 at 21:24

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.