简体   繁体   中英

Check CMAKE version using python

I'm building a project for first time and its really confusing. I've included a project through using gitmodules and I'm using visual studio and I want to static link that project in my own project. issue is, is that the project doesn't come with a visual studio solution so I'm left with running cmake on this, however I saw online through looking on GitHub that people use scripts to run all the prerequisite stuff for building. so I've made batch scripts and python scripts and its going well so far.

But I haven't been able to find anywhere online that shows how to get the cmake version using python.

I want the python script to detect if cmake installed or not and if it is installed then to check its version.

Current my python code looks like this

if cmake --version <= 3.22.1:
    exit(1)

this gives me errors though "SyntaxError: invalid syntax"

Running cmake --version in the terminal shows the version as expected. "cmake version 3.22.1"

Im trying to get the cmake version from the call to be used in an if statement in python rather than just calling cmake --version in python.

does anyone know how to do this? also if this is x,y problem please let me know I don't know what I'm doing!

thanks

Use Subprocess

subprocess = subprocess.Popen("cmake --version", shell=True, stdout=subprocess.PIPE)

subprocess_return = subprocess.stdout.read()

print(subprocess_return)

You now have the output of the command inside the subprocess_return variable, Now you can just parse it to get the version number.

import subprocess import re try: msg = subprocess.Popen("cmake --version", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.read().decode() # guess versions = msg.split()[2] pat = re.compile(r'[0-9]\.[0-9].+\.[0-9]') if pat.match(versions): print(versions.split(".")) else: print("Invalid!") except: print("Invalid!")

You can check CMake version against 3.22.1 like this:

import subprocess
from packaging import version

def get_cmake_version():
    output = subprocess.check_output(['cmake', '--version']).decode('utf-8')
    line = output.splitlines()[0]
    version = line.split()[2]
    return(version)

if version.parse(get_cmake_version()) < version.parse("3.22.1"):
    exit(1)

get_cmake_version runs cmake --version , getting its output with check_output() . Then with a combination of split() and splitlines() , it then gets the third word on the first line and returns it. Then we parse the version number returned by get_cmake_version() with version.parse from the packaging module and compare it to 3.22.1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM