如何在emacs中运行python程序

当编辑完python文件,如何绑定按键编译python文件,并在另一个buffer中显示输出结果

求教大佬分享

(compile “python foo.py”)

3 个赞
(defun python/run-current-file (&optional directory)
  "Execute the current python file."
  (interactive
   (list (or (and current-prefix-arg
                  (read-directory-name "Run in directory: " nil nil t))
             default-directory)))
  (when (buffer-file-name)
    (let* ((command (or (and (boundp 'executable-command) executable-command)
                        (concat "python3 " (buffer-file-name))))
           (default-directory directory)
           (compilation-ask-about-save nil))
      (executable-interpret (read-shell-command "Run: " command)))))

(define-key python-mode-map [f5] 'python/run-current-file)

报错,python-mode-map

错误是 (void-variable python-mode-map) ? 是的话就需要

(with-eval-after-load 'python 
  (define-key python-mode-map [f5] 'python/run-current-file))

it’s great ,完美,谢谢大佬指点,

在你的emacs中f5按键是否应该可以执行不同的文件类型:例如 c,python go 这些

如果是不同语言的文件, 可以看 http://ergoemacs.org/emacs/elisp_run_current_file.html

不过我觉得直接用 M-x compile 也足够用了

如果是比较短小的代码片段,可以用 org-mode 管理。

如果篇幅较长,需要写成单独文件,可以用 quickrun 运行,支持多种语言,并且可以为不同文件设置不同的编译/运行参数:

例如把这一段写在源代码文件里,它既可以提醒你编译条件(不至于过几个月回头看,忘了如何编译),也是能直接被 quickrun 使用的:

/*
  Local Variables:
  quickrun-option-cmd-alist: ((:command . "g++")
                              (:exec    . ("%c -std=c++0x -o %n %s"
                                           "%n apple orange melon"))
                              (:remove  . ("%n")))
  End:
*/
1 个赞

简单的一些脚本可以使用quickrun, 如果需要input, 可以使用这个

  (defun maple/run-python ()
    (interactive)
    (or (python-shell-get-process) (call-interactively 'run-python))
    (if (region-active-p)
        (python-shell-send-region (region-beginning) (region-end) t)
      (python-shell-send-buffer t)))
1 个赞

可以直接在eshell里面用python编译器运行,就像在终端中那样。

如果是用spacemacs 快捷键spc m c C

1 个赞

为了证明我也是大佬 我也说一个


(defun python/run-current-file (&optional directory)
  "Execute the current python file."
  (interactive
   (list (or (and current-prefix-arg
                  (read-directory-name "Run in directory: " nil nil t))
             default-directory)))
  (when (buffer-file-name)
    (let* ((default-directory directory)
           (compilation-ask-about-save nil))
      (make-comint-in-buffer "name" (get-buffer-create "*python run*")
                             "python" (buffer-file-name))
      (switch-to-buffer "*python run*"))))

我再说一个吧

第一步:

M-x run-python 启动一个python进程

第二步:

M-x python-shell-send-buffer 或 M-x python-shell-send-defun 或 M-x python-shell-send-region

自动给python进程输入代码

我还找到了更好的

用 elpy

1 个赞

或者用 spacemacs 的 Python layer

大佬应该不用evil 也应该不用spacemacs

一般也不用 Emacs。

论坛也应该不逛