1

I want to change the shebang string every time I create a new Python file, some projects use Python 2 and other use Python 3, so the shebang should change according to the value of a variable in the .dir-locals.el file of the project.

To generate the header text I use header2.el. There is the code I have so far:

(defvar-local shackra:var-python-ver 2
    "Indica que versión de Python estamos usando, Python2 o Python3")
(put 'shackra:var-python-ver 'safe-local-variable-values #'integerp)

;; configuración basica para python-mode y elpy-mode
(setf python-indent-guess-indent-offset nil
    python-indent 4
    python-indent-offset 4
    elpy-modules '(elpy-module-company
        elpy-module-eldoc
        elpy-module-pyvenv
        elpy-module-yasnippet)
    elpy-rpc-backend "jedi")

;; habilita elpy
(elpy-enable)

(defun shackra:python-switch-python-version ()
    "Cambia entre (i)Python2 o (i)Python3 dependiendo de ciertas variables"
    (if (eq shackra:var-python-ver 2)
        (setf elpy-rpc-python-command "python2"
            elpy-interactive-python-command "ipython2"))
        (setf elpy-rpc-python-command "python3"
        elpy-interactive-python-command "ipython"))

(defun shackra:header-python-shebang-coding ()
    "Inserta los famosos shebang (#!) y “coding”"
    (if (eq shackra:var-python-ver 2)
        (insert "#!/usr/bin/python2\n")
    (insert "#!/usr/bin/python3\n"))
    (insert header-prefix-string "-*- coding: utf-8 -*-\n\n"))

(add-hook 'python-mode-hook (lambda ()
    (electric-indent-local-mode -1)
    (shackra:python-switch-python-version)
    (setf make-header-hook '(shackra:header-python-shebang-coding))
    (auto-make-header)
    (py-autopep8-enable-on-save)))

If the content of a .dirs-locals.el for a directory is:

((python-mode
    (shackra:var-python-ver . 3)))

My configuration changes correctly in (shackra:python-switch-python-version), however, (shackra:header-python-shebang-coding) inserts the string #!/usr/bin/python2 when creating a new Python file inside that directory.

Why does this happens and how can I fix this?

  • Check if these functions interfere: (shackra:python-switch-python-version) (setf make-header-hook '(shackra:header-python-shebang-coding)) (auto-make-header) i.e. run only one of them, comparing the results in question. – Andreas Röhler May 25 '15 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.