Emacs/Python - 函数需要一个缩进块

Emacs/Python - function expected an indented block

我切换到 Emacs。我在 Emacs 中使用 Elpy 作为 IDE。我的设置是并排 windows,左边是一个缓冲区(脚本),我 write/edit 代码然后被发送到 IPython shell右 Ctrl-Enter。当我输入函数时:

 import numpy as np
 import pandas as pd

 data = pd.read_csv('spx_index.csv')

 def convert(x):
     return x.ix[:, 1:].set_index(x.ix[:, 0])

进入脚本(4-space 缩进)并按 Ctrl-Enter 两次我得到:

>>> ...   File "<stdin>", line 2
    return x.ix[:, 1:].set_index(x.ix[:, 0]) 
         ^
IndentationError: expected an indented block

但是,当我复制函数并将其直接粘贴到 IPython shell:

>>> def convert(x):
    return x.ix[:, 1:].set_index(x.ix[:, 0]) 
... ... 
>>> 

有效,功能已保存。

将函数 运行 直接从脚本获取到 shell 将是理想的。我无法想象必须将每个函数复制并粘贴到 shell.

要发送整个缓冲区,您可以按 C-c C-c 。您可以使用 C-c C-r 发送整个区域,您可以通过绑定以下函数发送您所在的当前行。以下函数本质上是 python-shell-send-buffer

的副本
(defun python-shell-send-line (&optional send-main msg)
  "Send the entire line to inferior Python process.
When optional argument SEND-MAIN is non-nil, allow execution of
code inside blocks delimited by \"if __name__== \='__main__\=':\".
When called interactively SEND-MAIN defaults to nil, unless it's
called with prefix argument.  When optional argument MSG is
non-nil, forces display of a user-friendly message if there's no
process running; defaults to t when called interactively."
  (interactive (list current-prefix-arg t))
  (save-restriction
    (widen)
    (python-shell-send-region (line-beginning-position) (line-end-position) send-main msg)))

;;这应该可以,但在您的 .emacs 文件中不起作用:

(defun mp-add-python-keys ()
  (interactive)
  (local-set-key (kbd "C-c C-n") 'py-execute-line))
(add-hook 'python-mode-hook 'mp-add-python-keys)