2013-07-15 20 views
15

我在vim中苦苦掙扎。
我還沒有找到我如何可以從python腳本(在vim函數中)將值導回到vim p.e.在vimscript中使用Python:如何將值從python腳本導出回vim?

function! myvimscript() 

    python << endpython 
    import vim, random, sys 
    s = vim.eval("mylist") 
    # do operation with variable "s" in python 
    endpython 

    " import variable "s" from above 
    " do operation with "s" in vimscript 
endfunction 

1)如何能在我的vim再次使用"s"(我怎麼可以導入"s"從Python代碼回到VIM)?

我無法找到如何使用vim.current.buffer與選擇。

function! myvimscript() 
    let startline = line("'<") 
    let endline = line("'>") 

    python << endpython 
    start = vim.eval("startline") 
    end = vim.eval("endline") 
    cb = vim.current.buffer 
    l = cb[start:end] 
    endpython 
endfunction 

2)我怎樣才能分配動態值"start""end""l"

+0

這是一個從bash腳本運行的python腳本嗎? –

+0

@TallPaul,Un pythonscript在vimscript中運行(並用vimrc中的地圖調用) – Reman

+0

相關:[如何從Python&Vimscript中的函數返回值?](http://stackoverflow.com/q/ 16756613)。 – glts

回答

16

首先,請確定啓動以大寫的函數名。

下面是你的兩個問題的例子。我希望它能幫助:

function! TestPy() range 

    let startline = line("'<") 
    let endline = line("'>") 
    echo "vim-start:".startline . " vim-endline:".endline 
python << EOF 
import vim 
s = "I was set in python" 
vim.command("let sInVim = '%s'"% s) 
start = vim.eval("startline") 
end = vim.eval("endline") 
print "start, end in python:%s,%s"% (start, end) 
EOF 
    echo sInVim 
endfunction 

首先我貼上一個小的測試輸出:選擇3,4,5,三線我的視覺和:call TestPy()

輸出我:

vim-start:3 vim-endline:5 
start, end in python:3,5 
I was set in python 

所以我將輸出解釋一下,您可能需要閱讀示例功能代碼以瞭解下面的註釋。

vim-start:3 vim-endline:5 #this line was printed in vim, by vim's echo. 
start, end in python:3,5 # this line was prrinted in py, using the vim var startline and endline. this answered your question two. 
I was set in python   # this line was printed in vim, the variable value was set in python. it answered your question one. 

我爲您的功能添加了一個range。因爲如果你沒有它,每個可視化選擇的行,vim都會調用你的函數一次。在我的例子中,該函數將被執行3次(3,4,5)。與範圍,它將視覺選擇作爲一個範圍。這個例子就足夠了。如果你的真實功能會做別的,你可以刪除range

range,更好用a:firstline and a:lastline。我使用line("'<")只是爲了保持它與您的代碼相同。

編輯與列表變量:

檢查此功能:

function! TestPy2() 
python << EOF 
import vim 
s = range(10) 
vim.command("let sInVim = %s"% s) 
EOF 
    echo type(sInVim) 
    echo sInVim 
endfunction 

,如果你把它的輸出是:

3 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

「3」 是指類型列表中(檢查type()函數)。下面一行是列表的字符串表示。

+0

偉大的解釋肯特!但是,如果's'不是一個字符串,而是一個列表。它給'vim.command(「let sInVim ='%s'」%s)' – Reman

+1

@Remonn檢查編輯 – Kent

+0

非常感謝。我會更多地研究你的答案。你給了我這麼多的信息。但現在一切正常! – Reman