iBoyko - "sort of" a website

Configuring Directory Environment Variables When Using Python in Emacs

An example of how to configure directory environment variables for python.el

Posted by Yakov Boyko on November 02, 2019

If you are trying to use Emacs for your Python programming needs, you are probably familiar with the Python major mode, which was originally started as Python.el

This mode is aware of directory-based environment variable configurations. That is, one can configure environment variables by creating a file called .dir-locals.el and populating it with an appropriate (associative) property list.

Here is an example of such file

  (python-shell-interpreter . "/home/user-name/miniconda3/envs/env-name/bin/python")
  (python-shell-interpreter-args . "/var/www/sites/project-name/project/manage.py shell")
  (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ")
  (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ")
  (python-shell-completion-setup-code . "from IPython.core.completerlib import module_completion")
  (python-shell-completion-string-code . "';'.join(module_completion('''%s'''))\n")
  (python-shell-completion-string-code . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
  (python-shell-virtualenv-root . "/home/user-name/miniconda3/envs/env-name")))


Some basic decoding for the entries is as follows:

  • python-shell-interpreter: The interpreter for shell interactions.
    Always set it to python or python2, if you are using iPython, Django will take care of enabling it itself when you use the shell.
  • python-shell-interpreter-args: Arguments to pass to the shell.
    This trick lets you start the Django shell by default when spawning shell processes for buffers.
  • python-shell-prompt-regexp: This is needed comint interaction with iPython.
    This helps comint to keep track of the prompt.
  • python-shell-prompt-output-regexp: This is needed comint interaction with iPython.
    Same as above
  • python-shell-completion-setup-code: Code to setup completion.
    All completion retrieval commands should get all they need from this code.
  • python-shell-completion-module-string-code: Tells comint how to autocomplete modules.
    Since comint can't use iPython completion by default because of limitations on shell escape codes, ipython.el makes it use this code to retrieve available completions.
  • python-shell-completion-string-code: This tells comint how to autocomplete stuff.
    Same as above
  • python-shell-extra-pythonpaths: Extra dirs where to find python modules.
    One can put all project apps in a separate folder and use this variable for that as it lets Emacs to know of this directory despite of the Django project.
  • python-shell-virtualenv-path: virtualenv path for the current project.
    This variable itself enables virtualenv for the current project. As soon as you visit a file the virtualenv will be detected and enabled for the file.