Search code examples
pythonwindowscmakebuild

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 statically link that project in my own project. The issue 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 is 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"

I'm 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.

I'm looking for a way do this natively in python, not through calling command lines in python.


Solution

  • 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.

    Note that the above subprocess.check_output() call throws FileNotFoundError when CMake is not installed. This isn't documented though. The documentation for check_output() says that it can throw CalledProcessError but doesn't mention FileNotFoundError.

    You'll probably want to handle these two errors with try/except.