25

What is the recommended way getting hold of the package version of a package in the $PYTHONPATH or sys.path?

I remember that the pkg_resource module has some functionality for this but I can not find any related information. Please don't point me to solution using a version.py file and reading it somehow. Using pkg_resources is the way to go but how exactly?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72

2 Answers2

29
>>> import pkg_resources
>>> pkg_resources.get_distribution("PIL").version
'1.1.7'
AdamKG
  • 13,678
  • 3
  • 38
  • 46
  • This gives me an error: `DistributionNotFound: The 'PIL' distribution was not found and is required by the application` – Gaurav Srivastava Dec 23 '21 at 01:34
  • PIL is just an example package name. You would use the name of whatever package you're trying to check the version of. – AdamKG Dec 23 '21 at 17:20
  • I have PIL installed on the environment, so the command should have worked. Actually, `pkg_resources.get_distribution('Pillow').version` worked for me. Other packages that worked are `numpy`, `scipy`. `os`, `math` did not work. – Gaurav Srivastava Dec 25 '21 at 20:07
1

I found it quite unreliable to use the various tools available (including the best one pkg_resources mentioned by this other answer), as most of them do not cover all cases. For example built-in modules and modules not installed but just added to the python path (by your IDE for example). Since we needed a reliable way to get the version of any package, module or submodule, I ended up writing getversion. It is quite simple to use:

from getversion import get_module_version
import foo
version, details = get_module_version(foo)

See the documentation for details.

smarie
  • 4,568
  • 24
  • 39