Running Python Programs from Emacs

Tips on running python from Emacs.

Setting-up

Python interpreter to use

If you have more than one version of python installed on your system you may want to tell emacs which one of those to use. The python interpreter that emacs will use is controlled by the py-python-command variable. You can set it with:

(setq py-python-command "/usr/local/bin/python2.3")

Associating files with python

Emacs will normally associate files ending with .py with python and enter python-mode if you open (visit) these files. You can associate other files with python through the use of the auto-mode-alist variable.

For example, scons is a popular build environment tool built on top of python. Its configuration files are in python themselves, so it is useful to be able to edit them in python-mode. This can be arranged by placing the following into your .emacs file:

(setq auto-mode-alist
      (cons '("SConstruct" . python-mode) auto-mode-alist))

Shell Environment

You can adjust the shell environment under which the python interpreter will run, including the content of the PYHTONPATH variable, using commands described in this entry.

Keystrokes

All of these work only in Python-mode, i.e., if you've open a file with a suffix .py.

  • C-c ! to start a python interpreter as a sub-process, or if already started, to switch to this buffer.
  • C-c C-c to send the entire current file to the interpreter
  • C-M-x to send the current function definition the interpreter
  • C-c ret to reload current file as python module