user3650925
user3650925

Reputation: 198

How to determine the version of a library

How to determine the version of a python library, from a python piece of code, when the library has no version attribute?

Here is the example of the Pyvisa library which had no version attribute initially. I have done the following code that returns unknown for the version when I can't determine it.

try:
    import visa
    from visa import VisaIOError, Error
    pyvisa_version=0.
    try:
        pyvisa_version=float(visa.__version__)
    except:
        pass
    if pyvisa_version >0.:
        print 'pyvisa version: %f ' % pyvisa_version
    else:
        print 'pyvisa version: unknown'
    if pyvisa_version <= 1.5:
        try:
            from visa import vpp43
        except:
            print 'Cannot import vpp43.'
except:
    print 'Cannot import visa'

Does anyone has a better solution when there is no version attribute?

Upvotes: 1

Views: 3868

Answers (2)

Paula Thomas
Paula Thomas

Reputation: 1190

Yes! This will get you the versions of every library on your system.

pip freeze

or for python 3

pip3 freeze

It will output a list to the terminal you've run it in.

Following the comment below:

import os
import glob
d = os.path.dirname('libname'.__file__)
dirs = glob.glob(d+'*')
for d in dirs:
if d.endswith('.dist-info'):
    d = d.split('/')
    f=d[-1]
    f = f.split('-')
    f = f[1:]
    f = ''.join(f)

and 'f[:-9]' now contains the version number.

Upvotes: 1

Derek Eden
Derek Eden

Reputation: 4638

you could try the pkg_resources package?

import pkg_resources
pkg_resources.get_distribution('visa').version

result - '1.0.0'

from what I've read previously, this method works when there is no version attribute and does not rely on pip either.

but this also depends on having this package installed..

EDIT

this specific package has a visa.version module which is just a .py file with the version in it..

file_loc = visa.version

then you could parse the version out of it? probably an easier way.. but an idea

Upvotes: 1

Related Questions