Emacs与Python更新模块
目前我在用emacs写一些Python代码,整体上运行得不错,但有一个问题让我有点烦。
每次我在自己写的模块里更新了什么,我都会重新评估一下这个缓冲区,但emacs里的Python shell却没有更新。我总是得结束Python进程,然后再重新启动它,才能看到更改。我发现emacs会把一些东西复制到一个临时目录去执行,所以我猜这可能和这个有关。
也许有人遇到过同样的问题并且已经解决了,所以如果能帮忙就太好了。
4 个回答
0
你可以在python-mode.el中添加一个函数来实现你想要的效果(前提是我理解你的请求没错)。把下面的内容放到你的Emacs初始化文件里:
(defun py-reload-file (buf)
"Reload buffer's file in Python interpreter."
(let ((file (buffer-file-name buf)))
(if file
(progn
;; Maybe save some buffers
(save-some-buffers (not py-ask-about-save) nil)
(let ((reload-cmd
(if (string-match "\\.py$" file)
(let ((f (file-name-sans-extension
(file-name-nondirectory file))))
(format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
f f f))
(format "execfile(r'%s')\n" file))))
(save-excursion
(set-buffer (get-buffer-create
(generate-new-buffer-name " *Python Command*")))
(insert reload-cmd)
(py-execute-base (point-min) (point-max))))))))
(defadvice py-execute-region
(around reload-in-shell activate)
"After execution, reload in Python interpreter."
(save-window-excursion
(let ((buf (current-buffer)))
ad-do-it
(py-reload-file buf))))
现在,当你在写Python程序时,可以选中一段代码,然后按 C-| 来执行这段代码,这样Python程序就会在Python解释器的窗口中重新加载(如果之前没有加载的话,就会导入它)。注意,这里是整个模块都会被重新加载,而不仅仅是你选中的那部分代码。如果你的Python文件还没有保存,系统会提示你保存。需要注意的是,在你之前提到的问题中提到的一些注意事项仍然适用(比如,如果你已经创建了从导入模块生成的类实例,或者实例化了其他对象等,它们不会被重新加载)。可能会出现一些问题,所以要小心哦!
2
我找到了一种更好的解决方案,不需要配置emacs:
只需执行
$ ipython profile create
这会在
$HOME/.ipython/profile_default/ipython_config.py
中创建一个ipython配置文件。
然后把以下内容放进去:
c = get_config()
c.TerminalInteractiveShell.editor = 'emacsclient'
c.InteractiveShellApp.extensions = [
'autoreload'
]
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
接着重启emacs。现在每次你在emacs中保存文件的更改时,ipython会自动重新加载它。
另外,我在我的emacs配置中有以下内容:
;; ------------------
;; misc python config
;; ------------------
(company-mode -1)
(elpy-enable)
(elpy-use-ipython "ipython")
(setq python-shell-interpreter "ipython" python-shell-interpreter-args "--simple-prompt --pprint")
(setq python-check-command "flake8")
(setq elpy-rpc-backend "jedi")
(setq elpy-rpc-python-command "python")
; https://github.com/gregsexton/ob-ipython/issues/28
(setq python-shell-completion-native-enable nil)
如果你想查看我完整的python配置,可以在这里找到:这里