Search code examples
pythonrequirements

How to check if all packages meet version requirements?


When running a script in Python interpreter, I want to check if I use the following versions:

absl-py==0.1.10
agate==1.6.0
agate-dbf==0.2.0
agate-excel==0.2.1
agate-sql==0.5.2
appnope==0.1.0

I can for example do this:

if absl-py.__version__ != "0.1.10":
    logging.error("update to version == 0.1.10")
    sys.exit() #

And repeat for all other packages. Is there a way to iterate through all the specified packages and raise and error when one if the conditions is not met?


Solution

  • You can do something like this and define the modules and versions in a dictionary:

    import pkg_resources
    
    module_versions = {"absl-py":"0.1.10", "agate":"1.6.0"}
    
    for module, v_req in module_versions.items():
        try:
            if pkg_resources.get_distribution(module).version != v_req:
                print(f"{module}, Required Version: {v_req}, Your Version: {v_inst}")
        except:
            print(f"{module} not installed")