question 291 Packaging & Databases · easy
Read a requirements file
A deploy tool needs the requirement lines from a requirements.txt, without the clutter people put around them. Write read_requirements(text). Follow pip's rules: a line starting with # is a comment, and so is the rest of a line after a # that has whitespace before it (a # inside a URL, such as #sha256=…, is not a comment). Lines starting with - are pip options (-r base.txt, --index-url …), not requirements.
Function
read_requirements(text)textthe file's content: one requirement per line, with comments, blank lines and option lines mixed in
Returnsthe requirement lines in order, each stripped of surrounding whitespace and of any trailing comment
Skipblank lines, comment lines and lines starting with
-Examples
callread_requirements('# Runtime Market reports\nrequests>=2.31\npandas>=2.2,<3 # dataframes\n\n-r base.txt\n')returns['requests>=2.31', 'pandas>=2.2,<3']
callread_requirements('')returns[]
callread_requirements('rich==13.7.1\n--index-url https://pypi.org/simple\n')returns['rich==13.7.1']