我正在编写一个python脚本来构建具有多种技术堆栈的项目。我需要检查所有先决条件是否已准备就绪,并且Maven是先决条件之一。
通常,Maven教程将要求用户设置环境变量M2_HOME
并将%M2_HOME%/bin
添加到路径。
使用下面的代码很容易检查环境变量,
if 'M2_HOME' not in os.environ:
print('Install maven firstly')
但是,如果用户未将M2_HOME
设置为环境变量,而是在路径中添加了pache-maven-x.x.x\bin
,则仍然可以认为Maven已成功安装,并且我认为后者更加全面。
那么,问题来了:我如何使用Python检查是否已安装Maven?
在我看来,可以从Python启动mvn
作为一个进程并检查输出是什么,例如通过调用mvn -v
。还有其他建议吗?
答案 0 :(得分:2)
您可以使用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')
答案 1 :(得分:1)
# 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
答案 2 :(得分:0)
您可以使用终端命令which mvn
,如果响应为mvn not found
,则应安装它。
p = subprocess.Popen(["which", "mvn"], stdout=subprocess.PIPE)
print p.communicate()
然后比较输出