在vim中执行python命令并获取输出

时间:2010-08-31 11:58:15

标签: python vim

当使用Python支持编译Vim时,您可以使用:python命令使用Python脚本编写Vim脚本。我如何使用它来执行命令并在光标下插入结果?例如,如果我要执行:python import os; os.listdir('aDirectory')[0],我希望返回的第一个文件名插入光标下。

编辑:为了澄清,我希望获得与去往终端,执行命令,复制结果和执行"+p相同的效果。

4 个答案:

答案 0 :(得分:5)

:,!python -c "import os; print os.listdir('aDirectory')[0]"

答案 1 :(得分:2)

您需要将其分配给当前行,您可以使用vim模块:

:python import os; import vim; vim.current.line=os.listdir('.')[0]

答案 2 :(得分:2)

以下对我来说很好: 在你想要的行中编写你想要执行的python代码。

import os
print(os.listdir('.'))

之后,在视觉上选择要在python中执行的行

:'<,'>!python

之后,python代码将替换为python输出。

答案 3 :(得分:0)

最后,我通过编写一个名为pyexec.vim的脚本解决了这个问题,并将其放入我的插件目录中。该剧本如下:

python << endpython
import vim
def pycurpos(pythonstatement):
    #split the python statement at ;
    pythonstatement = pythonstatement.split(';')
    stringToInsert = ''
    for aStatement in pythonstatement:
        #try to eval() the statement. This will work if the statement is a valid expression
        try:
            s = str(eval(aStatement))
        except SyntaxError:
            #statement is not a valid expression, so try exec. This will work if the statement is a valid python statement (such as if a==b: or print 'a')
            #if this doesn't work either, fail
            s = None
            exec aStatement


        stringToInsert += s if s is not None else ''

    currentPos = vim.current.window.cursor[1]
    currentLine = vim.current.line
    vim.current.line = currentLine[:currentPos]+stringToInsert+currentLine[currentPos:]

endpython

这对oneliner的预期效果如预期,但对于块后面的多个语句不起作用。因此python pycurpos('a=2;if a==3:b=4;c=6')将导致c 始终6,因为if块以其后的第一行结束。

但是对于快速而肮脏的python执行,这就是我想要的,脚本就足够了。