gpt4 book ai didi

python - 通用 :python command in vim?

转载 作者:太空狗 更新时间:2023-10-29 21:07:06 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com