代码之家  ›  专栏  ›  技术社区  ›  Senthil Kumaran

在vim/emacs中自动包含python导入语句?

  •  5
  • Senthil Kumaran  · 技术社区  · 16 年前

    在eclipse中,有一个方便的速记CTRL+SHIFT+o,它将根据所使用的类或模块自动包含import(include)语句。 你找到vim或emacs的插件了吗?

    2 回复  |  直到 16 年前
        1
  •  5
  •   alper resting    6 年前

    Ropemacs 有 rope-auto-import ,所以如果你写

    rmtree
    

    执行 M-x rope-auto-import

    from shutil import rmtree
    

    may not be a very wise idea.

    看到了吗 this SO post 有关设置Mac的信息。

        2
  •  2
  •   Ehvince    10 年前

    所以我对这个简单的功能很满意,它已经避免了我重复的动作。当我打电话的时候 my-python-import-add :

    • 有人问我要导入哪些模块(我可以给出一个逗号分隔的列表,如 os, sys, from foo import bar, re )
    • 它插入 import xxx 声明或 from … 你打字了。
    • 那一点(当然)没有动。

    M-x my-python-import-add os, sys, from foo import bar, requests 给了我:

    import os
    import sys
    
    import requests
    
    from foo import bar
    

    附言:发现一个警告:你需要已经有一个 import 声明。


    我们依靠 isort python包:

    pip install isort
    

    py-isort package (在Melpa中),

    因此,请阅读他们的帮助,以检查如何自定义排序功能。我自己想要一个单一的进口行,所以我设置

    (setq py-isort-options '("--force_single_line_imports"))
    

    功能:

    编辑 :我把它 in a gitlab repo

    :现在,提示符默认在点处提示单词

    (require 's)  ;; melpa
    (require 'dash)  ;; melpa
    
    (require 'py-isort)  ;; melpa
    
    (defun my-insert-import (to_insert)
      (newline)
      (if (s-starts-with? "from" (s-trim to_insert)) (insert (s-trim to_insert))
        (insert "import " to_insert))
      )
    
    (setq py-isort-options '("--force_single_line_imports"))
    
    
    (defun python-import-add (to_import)
      "Adds an import statement for every given module. Can give a comma-separated list of modules, like:
    M-x my-python-import-add RET os, sys, from foo import bar, re RET"
      (interactive "swhat to import ? ")
      (beginning-of-buffer)
      (save-excursion
        (search-forward-regexp "\\(^from \\)?.*import [a-z]+")  ;; if not found ?
        (end-of-line)
        ;; split the arguments by spaces:
        (setq to_insert (s-split "," to_import))
        ;; insert each elt of the list:
        (-map 'my-insert-import to_insert)
        ;; sort the imports: (set your py-isort options. See isort -h)
        (py-isort)
        )
      )
    

    我现在可能要做的就是抓住关键点(比如 sys.argv )建议违约。 =>完成

    我相信我们可以有一个有用的和完整的自动导入功能在emacs。