How could I get the version defined in setup.py
from my package (for --version
, or other purposes)?
To retrieve the version from inside your package at runtime (what your question appears to actually be asking), you can use:
import pkg_resources # part of setuptools
version = pkg_resources.require("MyProject")[0].version
If you want to go the other way 'round (which appears to be what other answer authors here appear to have thought you were asking), put the version string in a separate file and read that file's contents in setup.py
.
You could make a version.py in your package with a __version__
line, then read it from setup.py using execfile('mypackage/version.py')
, so that it sets __version__
in the setup.py namespace.
If you want a much simpler way that will work with all Python versions and even non-Python languages that may need access to the version string:
Store the version string as the sole contents of a plain text file, named e.g. VERSION
, and read that file during setup.py
.
version_file = open(os.path.join(mypackage_root_dir, 'VERSION'))
version = version_file.read().strip()
The same VERSION
file will then work exactly as well in any other program, even non-Python ones, and you only need to change the version string in one place for all programs.
By the way, DO NOT import your package from your setup.py as suggested in another answer here: it will seem to work for you (because you already have your package's dependencies installed), but it will wreak havoc upon new users of your package, as they will not be able to install your package without manually installing the dependencies first.