[英]Set Python project root in Emacs?
emacs-for-python (基于python.el
)提供了很好的功能来启动 Python 进程并直接从 Emacs 发送缓冲区(通常你用Cc Cc
来做)。 但是,这种方式会为每个缓冲区创建新进程,并将 Python 的工作目录设置为相应文件的目录。
相反,我希望将工作目录设置为项目根目录的单个 Python 进程。 或者甚至可能是几个进程,但从根目录开始,而不是模块的目录。
为什么我需要它? 都是关于进口的。 想象一下以下项目结构:
myproject
package1
__init__.py
mod1.py
package2
__init__.py
mod2.py
如果我在文件mod1.py
上启动 Python 进程,Emacs 会自动将工作目录设置为myproject/package1
,这样我就只能从同一个包中导入模块。 没有从其他包导入。 没有绝对进口。 疼痛。
目前我使用sys.path
的技巧,例如:
import sys, os
sys.path.insert(0, os.path.join(os.path.abspath(__file__), '..', '..'))
在每个模块的开头。 但这真的,真的,真的很丑陋和不方便。
那么有没有人有任何提示或技巧来为 Emacs 中的劣质进程设置 Python 的项目根目录?
我不熟悉 emacs-for-python,但找到项目根目录的路径很简单。
Projectile 提供了一个函数projectile-project-root
。 你可以在你的 mod1.py 缓冲区中调用它,它会返回"/path/to/myproject"
。 这假设 projectile 可以识别您的项目根目录,如果您使用某种 VCS 就可以了。
好的,这应该让你开始
(defvar my-python-shell-dir-setup-code
"import os
home = os.path.expanduser('~')
while os.path.isfile('__init__.py') and (os.getcwd() != home):
os.chdir('..')
del os")
(defun my-python-shell-dir-setup ()
(let ((process (get-buffer-process (current-buffer))))
(python-shell-send-string my-python-shell-dir-setup-code process)
(message "Setup project path")))
(add-hook 'inferior-python-mode-hook 'my-python-shell-dir-setup)
这是我们正在做的事情my-python-shell-dir-setup-code
是简单的 python 代码,用于查找project-dir
并设置它(它又快又脏,您可能想根据需要对其进行修改)。 然后我们添加一个inferior-python-mode-hook
(即my-shell-dir-setup
)来在创建shell 时在outerial shell 中执行python 代码。
上面接受的答案是正确的,只是上面接受的答案中有一个错误。 提出的问题的正确解决方案是:
(defvar my-python-shell-dir-setup-code
"import os
home = os.path.expanduser('~')
while (not os.path.isfile('__init__.py')) and (os.getcwd() != home):
os.chdir('..')
del os")
(defun my-python-shell-dir-setup ()
(let ((process (get-buffer-process (current-buffer))))
(python-shell-send-string my-python-shell-dir-setup-code process)
(message "Setup project path")))
(add-hook 'inferior-python-mode-hook 'my-python-shell-dir-setup)
不同之处在于while os.path.isfile('__init__.py') and (os.getcwd() != home):
应该是while (not os.path.isfile('__init__.py')) and (os.getcwd() != home):
如果没有__init__.py
文件,我们想后退一个目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.