代码之家  ›  专栏  ›  技术社区  ›  Eugene

如何使用python检查是否安装了maven

  •  1
  • Eugene  · 技术社区  · 7 年前

    我正在编写一个python脚本来构建一个具有多个技术栈的项目。我需要检查所有的先决条件是否准备好,Maven是先决条件之一。

    通常,maven教程会要求用户设置一个环境变量 M2_HOME 并添加 %M2_HOME%/bin 走上小路。

    很容易用下面的代码检查环境变量,

    if 'M2_HOME' not in os.environ:
        print('Install maven firstly')
    

    但是,如果用户没有设置 M2YHE 作为一个环境变量 pache-maven-x.x.x\bin 在这条路上,它仍然可以被认为是Maven的成功安装,我认为后者更全面。

    所以,问题来了 :如何使用python检查是否安装了maven?

    在我看来,有可能 mvn 例如,通过调用 mvn -v . 还有其他建议吗?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Amir    7 年前

    你可以使用 shutil.which 命令

    import shutil
    if not shutil.which("mvn"):
        print('Install maven firstly')
    

    编辑: 对于python2.7,可以使用 distutils.spawn.find_executable 而是:

    from distutils.spawn import find_executable
    if not find_executable("mvn"):
        print('Install maven firstly')
    
        2
  •  1
  •   ConorSheehan1    7 年前
    # tested on windows 7, python 2.7.13 
    import subprocess
    import os
    
    
    def version_available(cmd):
        try:
            # prints version and returns 0 if successulf
            output = subprocess.call([cmd, "--version"])
            return output == 0
        except OSError as e:
            # handle file not found error.
            if e.errno == os.errno.ENOENT:
                print("error please install " + cmd)
                return False
            else:
              # Something else went wrong, raise the exception
              raise
    
    version_available("mvn")    # returns False, prints error please install mvn
    version_available("python") # returns True,  prints Python 2.7.13
    
        3
  •  0
  •   Rohi    7 年前

    您可以使用终端命令 which mvn ,如果响应是 mvn not found 然后你应该安装它。

    p = subprocess.Popen(["which", "mvn"], stdout=subprocess.PIPE)
    print p.communicate()
    

    然后比较输出