user4533817
user4533817

Reputation:

Emacs/Python - function expected an indented block

I made the switch to Emacs. I am using Elpy within Emacs as an IDE. My setup is side-by-side windows, on the left is a buffer(script) where I write/edit the code which then gets sent to the IPython shell on the right with Ctrl-Enter. When I type the function:

 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])

into the script (4-space indentation) and press Ctrl-Enter twice I get:

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

However, when I copy the function and paste it directly into the IPython shell:

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

It works and the function is saved.

Getting the function to run directly from the script to the shell would be ideal. I can't imagine having to copy and paste every function into the shell.

Upvotes: 0

Views: 237

Answers (2)

anonin
anonin

Reputation: 1

;; this should work, but don't, in your .emacs file:

(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)

Upvotes: 0

Jules
Jules

Reputation: 973

To send the whole buffer you can press C-c C-c . You can send the whole region with C-c C-r and you can send the current line that you are by binding the following function. The following function is essentially a copy of 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)))

Upvotes: 0

Related Questions