ipython not reloading modules

2019-08-31 12:08发布

I'm running IPython in an emacs shell using:

;; Set IPython interpreter in my init.el
(defvar python-shell-interpreter "ipython")
(defvar python-shell-interpreter-args "-i")

Then:

  1. Start IPython with M-x run-python
  2. Run a program within IPython with %run myprog.py. myprog.py imports a module called mymodule.

I make changes to mymodule but when I run %run myprog.py again, it runs the original mymodule, not the changed code.

FWIW, I'm using emacs 24.5 prelude, on Windows 10 with Anaconda and Python 3.5.

1条回答
爷的心禁止访问
2楼-- · 2019-08-31 12:24

It turns out that IPython's %run command does not reload modules.

My current workaround is:

  1. Add the code below to ~/.ipython/profile_default/ipython_config.py
  2. Use $run myprog.py args

.

# this code in `~/.ipython/profile_default/ipython_config.py`
# get_config() is injected into the global namespace whilst
# config files are loaded
c = get_config()

# Autoreload modules
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

I didn't realise that %run does not reload modules because I'm used to using Spyder's runfile command, which does. It's nuts that %run doesn't and I'd like to submit a patch to fix it at some point.

On Windows, the HOME environment variable must be set so that the run-python command in emacs can read the IPython profile. If HOME is not set, you can add this to your init.el:

(add-hook 'inferior-python-mode-hook (lambda ()
                                       (progn
                                         (python-shell-send-string-no-output "%load_ext autoreload")
                                         (python-shell-send-string-no-output "%autoreload 2"))))
查看更多
登录 后发表回答