Python模式导入问题

22 投票
9 回答
6906 浏览
提问于 2025-04-15 21:43

我正在尝试把Emacs当作Python编辑器使用,单独评估(按C-c C-c)一个文件时一切正常,但当我评估一个导入了同一目录下另一个文件的文件时,就会出现一个错误,提示无法导入那个文件。

有没有人知道有什么解决办法?

提前谢谢大家。

补充一下,我是在一台运行Ubuntu的机器上使用Emacs23。

错误信息是,

  ImportError: No module named hlutils 

9 个回答

1

我在用 py-execute-buffer 的时候,可以很顺利地从同一个文件夹里导入本地模块。

你的问题可能和 py-execute-buffer 的工作方式有关:它会把当前的内容保存到一个临时文件(在 py-temp-directory 这个文件夹里),然后再把这个文件传给 Python。在你的情况下,系统可能会受到临时文件夹的影响。

还有一个方面:py-execute-buffer 对临时文件的处理方式会根据是否有 Python 解释器的缓冲区而有所不同。你可以试试在有解释器运行的情况下和没有的情况下(只需关闭解释器的缓冲区)来看看效果。

12

在之前的回答发布之后,现在有了一个新选项,可以改变默认的行为(就是把当前目录从路径中去掉),改为把当前工作目录包含在路径里。

所以只需要在你的 .emacs 文件中加上简单的一行代码:

(setq python-remove-cwd-from-path nil)

就可以解决这个问题了。

16

我觉得问题出在Emacs的python模式运行Python的方式上。如果我输入 M-x run-python,我看到的是:

>>> import sys
>>> '' in sys.path
False
>>> 

而如果我从命令行运行Python解释器,我看到的是:

>>> import sys
>>> '' in sys.path
True
>>> 

这似乎是因为在 run-python 的代码中,来自progmodes/python.el的以下代码:

(let* ((cmdlist
    (append (python-args-to-list cmd)
        '("-i" "-c" "import sys; sys.path.remove('')")))

这段代码没有注释,下面是一个有用的变更日志条目:

2008-08-24  Romain Francoise  <romain@orebokech.com>

        * progmodes/python.el (run-python): Remove '' from sys.path.

我认为这是Emacs中的一个bug。这里有一个解决方法,你可以把它放到你的.emacs文件里:

(defun python-reinstate-current-directory ()
  "When running Python, add the current directory ('') to the head of sys.path.
For reasons unexplained, run-python passes arguments to the
interpreter that explicitly remove '' from sys.path. This means
that, for example, using `python-send-buffer' in a buffer
visiting a module's code will fail to find other modules in the
same directory.

Adding this function to `inferior-python-mode-hook' reinstates
the current directory in Python's search path."
  (python-send-string "sys.path[0:0] = ['']"))

(add-hook 'inferior-python-mode-hook 'python-reinstate-current-directory)

撰写回答