9

I recently received a pull request to change my vim plugin to make it support python3. But these changes break the plugin for the vim on my Mac which seems to listen to python.

python import sys

versus

python3 import sys

Is there an elegant method to make the script in my plugin detect which statement it should use? Something like:

if has('python')
   python import ...
elseif if has('python3')
   python3 import ...
else
   finish
endif

Thanks.

5

If you want to avoid rewriting the Python script, put it in a separate file and use :pyfile or :py3file instead.

let script_path = expand('<sfile>:p:h') . '/script.py'

if !has('python') and !has('python3')
   finish
endif

execute (has('python3') ? 'py3file' : 'pyfile') script_path

This will load script.py that's in the same directory.

3

My technique for distinction of the python versions is to create a separate command (although this is in my .vimrc startup files, you can modify as needed for the plugin code.)

function! PyImports()
Py << EOF
import sys, os, .....
EOF
endfunction

if has('python')
  command! -nargs=* Py python <args>
  call PyImports()
elseif has('python3')
  command! -nargs=* Py python3 <args>
  call PyImports()
endif
3

Here's how youcompleteme does.

  1. Define a function for determining whether python3 is available:

    function! s:UsingPython3()
      if has('python3')
        return 1
      endif
        return 0
    endfunction
    
  2. then get the right python command:

    let s:using_python3 = s:UsingPython3()
    let s:python_until_eof = s:using_python3 ? "python3 << EOF" : "python << EOF"
    let s:python_command = s:using_python3 ? "py3 " : "py "
    

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.