簡體   English   中英

vim中的通用:python命令?

[英]Generic :python command in vim?

只要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

“ heredoc”( << EOF )語法僅限於腳本:py:perl等)命令; 您不能將它們與普通字符串一起使用。 而且在Vim中使用行繼續有點麻煩。

因此,我將Python代碼放在​​一個單獨的文件中,並將其傳遞給:py:py3命令。

let mycode = join(readfile(expand('~/mycode.py')), "\n")

if has('python')
    execute 'py ' . mycode
elseif has('python3')
    execute 'py3 ' . mycode
else
    echoe 'Your mother was a hamster'
endif

還有mycode.py腳本:

import sys
import vim
print('This is mycode', sys.version)

vim.command(':echo "Hello"')
print(vim.eval('42'))

從Python 2:

('This is mycode', '2.7.10 (default, May 26 2015, 04:16:29) \n[GCC 5.1.0]')
Hello
42

從Python 3開始:

This is mycode 3.4.3 (default, Mar 25 2015, 17:13:50)
[GCC 4.9.2 20150304 (prerelease)]
Hello
42

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM