17

我一直在使用 Emacs 编写 Python 2 代码。现在我的系统上安装了 Python 2.6 和 3.0,我还需要编写 Python 3 代码。

以下是在 /usr/bin 中设置不同版本的方式:

python -> python2.6*
python2 -> python2.6*
python2.6*

python3 -> python3.0*
python3.0*

有没有办法设置它,以便 Emacs 使用正确版本的 Python,具体取决于我使用的语言?例如,Cc Cc 当前运行缓冲区,但它总是调用 python2.6,即使我正在编写 Python 3 代码。

4

5 回答 5

10

如果您使用的是 python-mode.el,您可以尝试更改py-which-shell. 为了在每个文件的基础上做到这一点,你可以把

# -*- py-which-shell: "python3"; -*-

在文件的第一行 - 如果第一行以 . 开头,则在第二行#!。另一种选择是放

# Local Variables:
# py-which-shell: "python3" 
# End: 

在文件的末尾。也许您应该给出 python3 的完整路径,而不仅仅是“python3”。

于 2009-02-02T07:14:45.833 回答
4

答案是肯定的。如果你能区分 Python 2 和 Python 3,那么让 emacs 做你想做的事情就是一个简单的编程问题。

(define run-python (&optional buffer)
    (with-current-buffer (or buffer (current-buffer))
        (if (is-python3-p)
              (run-python3)
            (run-python2))))

(define-key python-mode-map (kbd "C-c C-c") #'run-python)

剩下要做的就是实施is-python3-prun-python3(等等)

于 2009-02-02T05:49:42.747 回答
3

我对这个答案的评论。

我写了 /t/min.py 它将在 python3 中运行良好但在 python2 中运行良好(字典理解在 python3 中有效)

/t/min.py 的内容

#!/usr/bin/python3
# -*- py-python-command: "/usr/bin/python3"; -*-
a = {i:i**2 for i in range(10)}
print(a)

请注意,shebang 表示 python3 和文件局部变量 py-python-command 也。

我还编写了 /t/min-py.el 以确保使用 python-mode.el(版本 5.1.0)而不是 python.el。

/t/min-py.el 的内容

(add-to-list 'load-path "~/m/em/lisp/")
(autoload 'python-mode "python-mode" "Python Mode." t)
;; (setq py-python-command "python3")

注意最后一行被注释掉了。

我使用以下命令启动 emacs:

emacs -Q -l /t/min-py.el /t/min.py &

现在 emacs 以我的备用 dotmacs /t/min-py.el 启动,它打开 /t/min.py。

当我按 Cc Cc 将缓冲区发送到 python 时,它说“for”部分是错误的,这表明正在使用 python2 而不是 python3。当我按抄送!启动python解释器,它说python 2.5已启动。

我什至可以将 /t/min.py 的第二行更改为:

# -*- py-python-command: "chunkybacon"; -*-

再做一次这个实验,emacs 仍然使用 python2。

如果 /t/min-py.el 的最后一行没有被注释掉,那么 Cc Cc 和 Cc !两者都使用python3。

于 2009-09-22T15:42:25.517 回答
2

关于 jrockway 的评论:

(defun is-python3-p () "Check whether we're running python 2 or 3."
  (setq mystr (first (split-string (buffer-string) "\n" t)))
  (with-temp-buffer
    (insert mystr)
    (goto-char 0)
    (search-forward "python3" nil t)))
(defun run-python () "Call the python interpreter."
  (interactive)
  (if (is-python3-p)
      (setq py-python-command "/usr/bin/python3")
    (setq py-python-command "/usr/bin/python"))
  (py-execute-buffer))

python3如果“python3”位于缓冲区的顶行(通常是shebang),这将调用。出于某种原因,(setq py-pyton-command ...)一旦您运行一次,就不允许您更改版本py-execute-buffer。除非您来回更改同一缓冲区上的文件,否则这应该不是问题。

于 2011-05-15T06:39:38.130 回答
1

以目前的python-mode.elshebang很荣幸。

交互式地打开一个 Python shell

M-x pythonVERSION    
M-x python

将调用已安装的默认值。

http://launchpad.net/python-mode

于 2012-07-26T17:27:19.233 回答