开发者

How do I get the version of an installed module in Python programmatically?

For the modules:

required_modules = ['nose', 'coverage', 'webunit', 'MySQLdb', 'pgdb', 'memcache']

and programs:

required_programs = ['psql', 'mysql', 'gpsd', 'sox', 'memcached']

Something like:

# Report on the versions of programs installed
for module in required_modules:
    try:开发者_如何学C
        print module.__version__
    except:
        exit


Unfortunately, module.__version__ isn't present in all modules.

A workaround is to use a package manager. When you install a library using easy_install or pip, it keeps a record of the installed version. Then you can do:

import pkg_resources
version = pkg_resources.get_distribution("nose").version


I found it quite unreliable to use the various tools available (including the best one pkg_resources mentioned by moraes' answer), as most of them do not cover all cases. For example

  • built-in modules
  • modules not installed but just added to the python path (by your IDE for example)
  • two versions of the same module available (one in python path superseding the one installed)

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜