Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Last active December 2, 2015 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpotlightKid/486c711a3c14c70edb1a to your computer and use it in GitHub Desktop.
Save SpotlightKid/486c711a3c14c70edb1a to your computer and use it in GitHub Desktop.
Read Python dependencies from requirements file and strip off version numbers.
def parse_requirements(requirements, ignore=('setuptools',)):
"""Read dependencies from file and strip off version numbers."""
with open(requirements) as f:
packages = set()
for line in f:
line = line.strip()
if line.startswith(('#', '-r', '--')):
continue
if '#egg=' in line:
pkg = line.split('#egg=')[1]
else:
pkg = line.split('==')[0]
if pkg not in ignore:
packages.add(pkg)
return packages
if __name__ == '__main__':
import sys
print("\n".join(sorted(parse_requirements(
sys.argv[1] if sys.argv[1:] else 'requirements.txt'))))
import re
def parse_requirements(requirements, ignore=('setuptools',)):
"""Read dependencies from file and strip off version numbers.
Supports extra requirements and '>=' and '<=' version qualifiers.
"""
with open(requirements) as f:
packages = set()
for line in f:
line = line.strip()
if not line or line.startswith(('#', '-r', '--')):
continue
# XXX: Ugly hack!
extras = []
def get_extras(match):
extras.append(match.group(1))
line = re.sub(r'\s*\[(.*?)\]', get_extras, line)
if '#egg=' in line:
line = line.split('#egg=')[1]
pkg = re.split('[=<>]=', line)[0].strip()
if pkg not in ignore:
if extras:
pkg = 'pkg [%s]' % extras[0]
packages.add(pkg)
return packages
if __name__ == '__main__':
import sys
print("\n".join(sorted(parse_requirements(
sys.argv[1] if sys.argv[1:] else 'requirements.txt'))))
--find-links http://foo.com/pypi
# development
-r requirements-dev.txt
# production
foo
bar==1.0
broken<=1.9
newandshiny >= 3.0
bigpackage [frob]
bloated==10.1 [gargle,fizzle]
-e git+http://git.projects.org/MyProject/#egg=AProject
-e git+http://git.projects.org/OtherProject/#egg=OtherProject==2.7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment