Monday, December 26, 2011

Set up python in emacs

There are lots of version of python, We have to face different python in one system. I use python25 and python27 to develop GoogleAppEngine and use python26 to develop SinaAppEngine. I want to try python32. So following I will set up python with emacs step by step.

Firstly we install all python to be used. Such as python25, python26 and python27. I put all of them to "d:/home/program/".

Run emacs and find file .emacs. Add following code to set python27's root in emacs's path.

(setq pythonversion "27")
(setq program-path "d:/home/program/")
(setenv "PATH" (concat (concat program-path"python"pythonversion";") (getenv "PATH")))

Then add following function to switch between pythons.

(defun* zxy-switch-python-version (&optional (pver nil))
  "Swith python version at runtime"
  (interactive)
  (if (equal nil pver)
      (let ((tempver (read-string (format "[zxy] Swith to which version of python (default %s)? "
                                          pythonversion) nil nil pythonversion nil)))
        (setq pver tempver)))
  (unless (file-exists-p (concat program-path"python"pver""))
    (error (format "[zxy] Cannot find python%s!" pver)))
  (message (format "[zxy] Switch to python%s." pver))
  (setq pythonversion pver)
  (setenv "PATH" (concat (concat program-path"python"pythonversion";") (getenv "PATH"))))

Set up python-mode as following.

;; emacs python
(require 'python)
(defun zxy-python-compile ()
  "Use compile to run python programs"
  (interactive)
  (compile (concat "python " (buffer-name))))
(setq compilation-scroll-output t)
(define-key python-mode-map "\C-cc" 'zxy-python-compile)

Restart emacs and open a py file. M-x zxy-python-compile will run this file in a new buffer. M-x zxy-switch-python-version help to switch python version.

No comments:

Post a Comment