只要vim是使用+python功能构建的,就可以在vim脚本中嵌入一些python代码。

function! IcecreamInitialize()
python << EOF
class StrawberryIcecream:
    def __call__(self):
        print('EAT ME')
EOF
endfunction

但是,有些人使用+python3构建了vim。这为vim插件带来了一些兼容性问题。是否有通用命令调用计算机上安装的任何python版本?

最佳答案

该代码段可以确定我们使用的是哪个Python版本并切换到该版本(Python代表已安装的该版本)。

if has('python')
    command! -nargs=1 Python python <args>
elseif has('python3')
    command! -nargs=1 Python python3 <args>
else
    echo "Error: Requires Vim compiled with +python or +python3"
    finish
endif

要加载python代码,我们首先要弄清楚它的位置(与Vim脚本在同一目录下):
execute "Python import sys"
execute "Python sys.path.append(r'" . expand("<sfile>:p:h") . "')"

然后检查python模块是否可用。如果没有,请重新加载它:
Python << EOF
if 'yourModuleName' not in sys.modules:
    import yourModuleName
else:
    import imp
    # Reload python module to avoid errors when updating plugin
    yourModuleName = imp.reload(yourModuleName)
EOF

两种调用方式:
1。
" call the whole module
execute "Python yourModuleName"

" call a function from that module
execute "Python yourModuleName.aMethod()"

2。
" Call a method using map
vnoremap <leader> c :Python yourModuleName.aMethod()<cr>

" Call a module or method using Vim function
vnoremap <leader> c :<c-u> <SID>yourFunctionName(visualmode())<cr>
function! s:YourFunctionName(someName)
    Python YourFunctionName.aMethod(a:someName)
    Python YourFunctionName
endfunction

关于python - 通用:python command in vim?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30944325/

10-15 08:38
查看更多