python - Get pip/setuptools version of package from within the package? -


i have package using setuptools it's deployment. want have function within package (cli tool) reports version of package. should report version field used in call setup. there way can access value on installed package?

for example, setup.py calls setup version = '0.1.6' , installes command line tool tool. want call tool --version prints version 0.1.6.

it's common practice list in package's main __init__.py file. instance, if package called sample, , lived in sample directory, have sample/__init__.py file this:

__version__ = '0.1.6'  def version():     return __version__ 

and make use of want in cli interface.

in setup.py, if wish can read value code in order not create redundancy, this:

import os.path  here = os.path.abspath(os.path.dirname(__file__))  # read version number source file. # why read it, , not import? # see https://groups.google.com/d/topic/pypa-dev/0pkjvpcxtzq/discussion def find_version(*file_paths):     # open in latin-1 avoid encoding errors.     # use codecs.open python 2 compatibility     codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') f:         version_file = f.read()      # version line must have form     # __version__ = 'ver'     version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",                               version_file, re.m)     if version_match:         return version_match.group(1)     raise runtimeerror("unable find version string.")  setup(     name="sample",     version=find_version('sample', '__init__.py'),     # ... etc 

for lots more discussion on different ways implementing sort of goal, please check http://packaging.python.org/en/latest/tutorial.html#version


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -