Reputation: 31871
I have a package using setuptools
for it's deployment. I want to have a function within the package (CLI tool) which reports the version of the package. This should report the version
field used in the call to setup
. Is there a way I can access this value on the installed package?
For example, my setup.py
calls setup
with version = '0.1.6'
and also installes a command line tool tool
. I want that a call to tool --version
prints the version 0.1.6
.
Upvotes: 0
Views: 236
Reputation: 5420
It's often common practice to list this in your package's main __init__.py
file. For instance, if you package was called sample
, and lived in the sample
directory, you would have a sample/__init__.py
file with something like this:
__version__ = '0.1.6'
def version():
return __version__
And make use of that however you want in your CLI interface.
In your setup.py
, if you wish you can read this value from your code in order not to create redundancy, something like this:
import os.path
here = os.path.abspath(os.path.dirname(__file__))
# Read the version number from a source file.
# Why read it, and not import?
# see https://groups.google.com/d/topic/pypa-dev/0PkjVpcxTzQ/discussion
def find_version(*file_paths):
# Open in Latin-1 so that we avoid encoding errors.
# Use codecs.open for Python 2 compatibility
with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f:
version_file = f.read()
# The version line must have the form
# __version__ = 'ver'
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name="sample",
version=find_version('sample', '__init__.py'),
# ... etc
For lots more discussion on different ways to implementing this sort of goal, please check http://packaging.python.org/en/latest/tutorial.html#version
Upvotes: 2