How do you run Python code using Emacs?

If you are using emacs24 this should be the default (in emacs23 you need python.el, not python-mode.el):

In a python buffer:

  • C-c C-z : open a python shell
  • C-c C-c : run the content of the buffer in the opened python shell
  • C-c C-r : run the selected region in the python shell

default python shell is “python”, if you need to use ipython you can use this conf in your .emacs

(setq
 python-shell-interpreter "ipython"
 python-shell-interpreter-args "--colors=Linux --profile=default"
 python-shell-prompt-regexp "In \\[[0-9]+\\]: "
 python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
 python-shell-completion-setup-code
 "from IPython.core.completerlib import module_completion"
 python-shell-completion-module-string-code
 "';'.join(module_completion('''%s'''))\n"
 python-shell-completion-string-code
 "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")

provided that you have ipython installed in your system of course 🙂

ipython>=5 has a auto-complete feature which breaks the emacs sub-shell, you can fix this by changing this line

python-shell-interpreter-args "--colors=Linux --profile=default"

and add --simple-prompt.

It will allow you to see ipython correctly but for some reason I did not get yet the auto-completion in emacs is not as effective as it used to be.

Leave a Comment

tech