开发者

Check version of Python library that doesn't define __version__

I'm dealing with a Python library that does not define the __version__ variable (sqlalchemy-migrate), and I want to have different behavior in my code based on what version of the library I have installed.

Is there a way to check at ru开发者_如何学编程ntime what version of the library is installed (other than, say, checking the output of pip freeze)?


This being Python, the accepted way of doing this is generally to call something in the library that behaves differently depending on the version you have installed, something like:

import somelibrary
try:
    somelibrary.this_only_exists_in_11()
    SOME_LIBRARY_VERSION = 1.1
except AttributeError:
    SOME_LIBRARY_VERSION = 1.0

A more elegant way might be to create wrapper functions.

def call_11_feature():
    try:
        somelibrary.this_only_exists_in_11()
    except AttributeError:
        somelibrary.some_convoluted_methods()
        somelibrary.which_mimic()
        somelibrary.the_11_feature()


pkg_resources may help, but you'll need to use the package name:

>>> import pkg_resources
>>> env = pkg_resources.Environment()
>>> env['sqlalchemy-migrate'][0].version
'0.6.2.dev'


If the library doesn't know its own version, then you are basically SOL. However, if one of the versions you want to support would raise an exception if the code went down the "wrong" path, you could use a try/except block.


Occasionally you can evaluate the path of the library and it will be in there somewhere... /usr/lib/python2.6/site-packages/XlsXcessive-0.1.6-py2.6.egg

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜