ErgoEmacsEmacsLispBlogEmacsLispBuy Tutorial
Web Hosting by 1&1

Emacs Lisp: Python 2to3 Wrapper

Xah Lee,

Here's a handy emacs lisp wrapper for converting current buffer's python 2 script to python 3.

(defun python-2to3 ()
  "Convert current buffer from python 2 to python 3.

This command calls python3's script 「2to3」. A backup will be generated by 「2to3」 and named “.bak”."
  (interactive)
  (let* (
         (fName (buffer-file-name))
         (fSuffix (file-name-extension fName))
         )
    (when (buffer-modified-p)
      (progn
        (when (y-or-n-p "Buffer modified. Do you want to save first?")
          (save-buffer) ) ) )

    (if (or (string-equal fSuffix "py") (string-equal fSuffix "py3") )
        (progn
          (shell-command (format "2to3 -w %s" fName))
          (revert-buffer  "IGNORE-AUTO" "NOCONFIRM" "PRESERVE-MODES")
          )
      (progn
            (error "file 「%s」 doesn't end in “.py” or “.py3”." fName)
            )
      )
    ))

A handy command to go with it is Emacs Lisp: Execute/Compile Current File

blog comments powered by Disqus