在Emacs中将Python项目设置为root? [英] Set Python project root in Emacs?

查看:141
本文介绍了在Emacs中将Python项目设置为root?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

emacs-for-python (基于python.el)提供了很好的功能来启动Python进程并从Emacs直接向其中发送缓冲区(通常使用C-c C-c来执行).但是,通过这种方式为每个缓冲区创建了新进程,并将Python的工作目录设置为相应文件的目录.

emacs-for-python (based on python.el) provides nice capability to start Python process and send buffer there right from Emacs (normally you do it with C-c C-c). However, this way new process is created for every buffer, and Python's working directory is set to the directory of corresponding file.

相反,我想将工作目录设置为项目的根目录的单个Python进程.甚至可能有几个进程,但始于根目录,而不是模块目录.

Instead, I'd like to have single Python process with working directory set to the root of the project. Or maybe even several processes, but started at the root directory, not the directory of the module.

我为什么需要它?一切都与进口有关.想象以下项目结构:

Why do I need it? It's all about imports. Imagine following project structure:

myproject
   package1
      __init__.py
      mod1.py
   package2
      __init__.py
      mod2.py

如果我在文件mod1.py上启动Python进程,Emacs会自动将工作目录设置为myproject/package1,这样我就只能从同一软件包中导入模块.没有从其他软件包导入.没有绝对进口.痛.

If I start Python process on file mod1.py, Emacs will automatically set working directory to myproject/package1 so that I will be restricted to importing modules from the same package only. No imports from other packages. No absolute imports. Pain.

当前,我对sys.path使用技巧,例如:

Currently I use a trick with sys.path, something like:

import sys, os
sys.path.insert(0, os.path.join(os.path.abspath(__file__), '..', '..'))

在每个模块的开头.但这确实非常丑陋且不便.

at the beginning of each module. But this is really, really, really ugly and inconvenient.

那么,有人在Emacs中为劣等流程设置Python项目根目录有任何技巧或窍门吗?

So does anybody have any tips or tricks to set up Python's project root for inferior process in Emacs?

推荐答案

好的,这应该可以帮助您入门

OK this should get you started

(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是查找并设置project-dir的简单python代码(它又快又脏,您可能需要根据需要对其进行修改).然后,添加inferior-python-mode-hook(即my-shell-dir-setup),以便在每次创建外壳时在下层外壳中执行python代码.

Here is what we are doing my-python-shell-dir-setup-code is simple python code to find project-dir and set it (it quick and dirty you may want to modify it according to your needs). Then we add a inferior-python-mode-hook (i.e. my-shell-dir-setup) to execute the python code in out inferior shell whenever the shell is created.

这篇关于在Emacs中将Python项目设置为root?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆