2014-12-05 140 views
1

我正在尝试为VIM创建一个Python插件,它将检测当前项目是否为Android项目。不幸的是,我无法让它将布尔值返回给VIM。从VIM内部调用插件不会输出任何内容。下面的代码使用print命令,但我也试过vim.command("return {value}")并在脚本中设置vim变量。任何见解?VIM/Python无法将值返回给VIM

我有这些内容的插件文件

if !has('python') 
    echo "Error: Required vim compiled with +python" 
    finish 
endif 


" Get local path for the script, so we can import other files 
let s:script_folder_path = escape(expand('<sfile>:p:h'), '\') 
let s:python_folder_path = s:script_folder_path . '/../python/' 

" Start the python file in the scriptdir 
function! s:startPyfile(fileName) 
    execute "pyfile " . s:python_folder_path . a:fileName 
endfunction 
command! Detect call Detect() 
function! Detect() 
    call s:startPyfile("vim_detect.py") 
endfunction 

这就要求vim_detect.py包含该

#! /usr/bin/env python 

import vim 
import os 
import sys 

# Add current scriptdir to import sources 
current_script_dir = vim.eval('s:python_folder_path') 
sys.path.append(current_script_dir) 

class VimDetect: 

    def executeCommand(self): 
     if self.isAndroidGradleProject(): 
      print 1 
     else: 
      print 0 


    def isAndroidGradleProject(): 
     if(isGradleProject() and isAndroidProject()): 
      return True 
     else: 
      return False 


    def isGradleProject(): 
     if findFileInDirectory("build.gradle"): 
      return True 
     else: 
      return False 

    def isAndroidProject(): 
     if findFileInDirectory("AndroidManifest.xml"): 
      return True 
     else: 
      return False 

    def findFileInDirectory(filename): 
     top = os.getcwd() 

     matches = 0 
     for root, dirnames, files in os.walk(top): 
      for file in fnmatch.filter(files, filename): 
       matches = matches + 1 
     if matches > 0: 
      return True 
     else: 
      return False 
+2

你的python文件除了导入之外什么都不做,而且'#添加当前scriptdir来导入源文件'这个类从来没有实例化过。 – Kent 2014-12-05 09:24:25

+0

您可能想看看似乎与您的目标相似的[projectionist.vim](https://github.com/tpope/vim-projectionist) – 2014-12-05 15:13:42

回答

3

正如其他人评论,您的示例代码(你应该已经凝结为最小的例子)实际上并没有被调用。我已经回到从Python这样的结果的方法是通过设置Vim的变量,就像这样:

strValue = "just a test" 
vim.command("let python_result = '%s'" % str(strValue).replace("'", "''")) 

对于一个布尔值,只是返回0/1的数量,简化的逻辑:

vim.command("let python_result = %d" % int(boolValue)) 
+0

作出了这些更改。仍然没有工作。设置适当的变量范围并且现在可以工作!谢谢! – 2014-12-06 02:18:49

+0

@Ingo Karkat伟大的'strValue'解决方案,但我注意到它在每一行末端都放上了一个'^ M'符号。 – Reman 2016-02-28 18:33:06