TIL: 自动使用项目虚拟环境的 Python
在 Emacs 里按 C-c C-p 打开 Python shell,默认用的是系统 Python。如果项目有虚拟环境,shell 里就找不到项目安装的包。
Einar Mostad 写了一个函数,自动在项目目录中递归查找 Python 可执行文件,找到就用虚拟环境的,找不到就用系统的:
(defun emo-python-virtualenv () "Sets the python shell to python from a virtual environment if one exists." (when (project-current) (let ((pythonpath (nth 0 (directory-files-recursively (nth 2 (project-current)) (if (eq system-type 'gnu/linux) "python$" "python.exe$"))))) (when (file-exists-p pythonpath) (setq-local python-shell-interpreter pythonpath)))))
加到 python-mode-hook 上,每次打开 Python 文件时自动设置:
(add-hook 'python-mode-hook 'emo-python-virtualenv)
三个关键点:
directory-files-recursively接受正则表达式,用"python$"匹配虚拟环境bin/目录下的 Python 可执行文件(不匹配python3、python-config等)project-current返回当前项目信息,(nth 2 (project-current))取项目根目录setq-local把python-shell-interpreter设为 buffer-local,不影响其他 buffer
参考:Use python shell from virtual environment if there is one in Emacs