Reputation: 841
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?
Upvotes: 1
Views: 523
Reputation: 1359
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")
Upvotes: 1
Reputation: 34282
You can receive the list of the installed packages using setuptools' pkg_resources
:
import pkg_resources
package_versions = {
p.project_name: p.version for p in pkg_resources.working_set
}
Now you can iterate through your file and compare the versions in it with those in the package_versions
dict.
Upvotes: 1
Reputation: 2441
You can use the following code to check if the packages exist (make sure to create requirements.txt
first):
with open("requirements.txt") as f:
packages = f.read().split("\n")
for package in packages:
package_name, package_version = package.split("==")
package_name = "_".join(package_name.split("-"))
exec(f"""\
try:
import {package_name}
except ImportError:
print("{package_name} doesn't exist")
else:
if not {package_name}.__version__== '{package_version}':
print(f"{package_name} is not up to date")""")
Upvotes: 1