Skip to content

Instantly share code, notes, and snippets.

@techtonik
Last active June 18, 2019 15:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techtonik/4066623 to your computer and use it in GitHub Desktop.
Save techtonik/4066623 to your computer and use it in GitHub Desktop.
Python - setup.py - read version without importing (2/3 compatible)
"""
# This snippet is in public domain
# https://gist.github.com/techtonik/4066623/
# Minified (Python 2.6+, 3+ compatible):
import io
from os.path import dirname, join
def get_version(relpath):
'''Read version info from a file without importing it'''
for line in io.open(join(dirname(__file__), relpath), encoding='cp437'):
if '__version__' in line:
if '"' in line:
# __version__ = "0.9"
return line.split('"')[1]
elif "'" in line:
return line.split("'")[1]
# Minified (Python 2.5+, 3+ compatible):
from os.path import dirname, join
def get_version(relpath):
'''Read version info from a file without importing it'''
for line in open(join(dirname(__file__), relpath), 'rb'):
# Decode to unicode for PY2/PY3 in a fail-safe way
line = line.decode('cp437')
if '__version__' in line:
if '"' in line:
# __version__ = "0.9"
return line.split('"')[1]
elif "'" in line:
return line.split("'")[1]
# Usage
version=get_version('module.py')
print(version)
"""
# Full Python 2.5+, 3.x compatible version
def get_version(relpath):
"""Read version info from a file without importing it"""
from os.path import dirname, join
if '__file__' not in globals():
# Allow to use function interactively
root = '.'
else:
root = dirname(__file__)
# The code below reads text file with unknown encoding in
# in Python2/3 compatible way. Reading this text file
# without specifying encoding will fail in Python 3 on some
# systems (see http://goo.gl/5XmOH). Specifying encoding as
# open() parameter is incompatible with Python 2
# cp437 is the encoding without missing points, safe against:
# UnicodeDecodeError: 'charmap' codec can't decode byte...
for line in open(join(root, relpath), 'rb'):
line = line.decode('cp437')
if '__version__' in line:
if '"' in line:
# __version__ = "0.9"
return line.split('"')[1]
elif "'" in line:
return line.split("'")[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment