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.
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
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.
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.
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
Here is what we are doing
my-python-shell-dir-setup-code
is simple python code to findproject-dir
and set it (it quick and dirty you may want to modify it according to your needs). Then we add ainferior-python-mode-hook
(i.e.my-shell-dir-setup
) to execute the python code in out inferior shell whenever the shell is created.