目前我正在使用Emacs编写一些Python代码,到目前为止它的表现还不错,只有一个问题真的有点烦人。
每当我更新自己编写的模块中的内容时,我都需要重新评估缓冲区,但是在Emacs内部的Python shell中,这个模块并没有得到更新。我总是不得不结束Python进程并重新启动才能得到更改。我发现Emacs会将某些东西复制到临时目录以执行它们,所以我想这可能与此有关。
也许有人已经遇到过同样的问题并解决了它,所以希望能得到帮助。
目前我正在使用Emacs编写一些Python代码,到目前为止它的表现还不错,只有一个问题真的有点烦人。
每当我更新自己编写的模块中的内容时,我都需要重新评估缓冲区,但是在Emacs内部的Python shell中,这个模块并没有得到更新。我总是不得不结束Python进程并重新启动才能得到更改。我发现Emacs会将某些东西复制到临时目录以执行它们,所以我想这可能与此有关。
也许有人已经遇到过同样的问题并解决了它,所以希望能得到帮助。
$ ipython profile create
这应该在IPython中创建配置文件
$HOME/.ipython/profile_default/ipython_config.py
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配置,请点击这里
。您可以建议一个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))))
我建议使用Elpy,如此处所讨论。
将以下内容添加到您的Emacs配置文件中:
(defun my-restart-python-console ()
"Restart python console before evaluate buffer or region to avoid various uncanny conflicts, like not reloding modules even when they are changed"
(interactive)
(if (get-buffer "*Python*")
(let ((kill-buffer-query-functions nil)) (kill-buffer "*Python*")))
(elpy-shell-send-region-or-buffer))
(global-set-key (kbd "C-c C-x C-c") 'my-restart-python-console)
重新启动您的Emacs,使用代码C-c C-x C-c
运行。
简而言之,此代码有一个"if语句",用于检查是否打开了Python缓冲区。这将有助于能够在开发的任何时间运行C-c C-x C-c
,即使没有已经打开的Python进程。另一个部分是kill-buffer-query-functions
,它忽略了杀死Python缓冲区的提示。