pip-requirements-parser
pip-requirements-parser is a Python library designed for robustly parsing `pip` requirement files. It distinguishes itself by leveraging `pip`'s own internal parsing logic, ensuring high accuracy in handling the diverse and often complex `pip` requirement format. The library provides a stable, offline API for parsing, making it suitable for environments where network access is restricted or where precise `pip`-compatible parsing is critical. It is currently at version 32.0.1 and aims for a stable API for its users, despite the inherent complexities of `pip`'s internal requirement file format.
Warnings
- gotcha The `pip` requirements file format is tightly coupled with `pip`'s internal implementation details and command-line options, making it notoriously difficult to parse correctly. While `pip-requirements-parser` aims to provide a stable API by incorporating `pip`'s own logic, users should be aware that the underlying `requirements.txt` format is not a stable public API and its full syntax can evolve with `pip` releases.
- gotcha It is generally discouraged to parse `requirements.txt` files directly to populate `install_requires` in `setup.py` or `pyproject.toml` for package distribution. Packaging metadata (e.g., in `pyproject.toml`'s `[project]` section) should use PEP 508 compliant specifiers for abstract dependencies, while `requirements.txt` is typically for concrete/pinned dependencies of applications.
- gotcha Unlike `pip` itself, which might perform network requests during its operations (e.g., resolving VCS requirements or fetching metadata), `pip-requirements-parser` is designed to work entirely offline. It parses the syntax without making external network calls.
Install
-
pip install pip-requirements-parser
Imports
- parse
import requirements for req in requirements.parse(req_string):
Quickstart
import requirements
req_string = """
django==3.2.1
requests>=2.25.1,<3.0.0
-e git+https://github.com/my/project.git#egg=myproject
"""
# Parse a string of requirements
for req in requirements.parse(req_string):
print(f"Name: {req.name}, Specs: {req.specs}, Vcs: {req.vcs}, Url: {req.url}")
# You can also parse from a file-like object
# with open('requirements.txt', 'r') as f:
# for req in requirements.parse(f):
# print(f"Name: {req.name}, Specs: {req.specs}")