We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
pip freeze --requirement doesn't accept inline comments
- Pip version: 8.1.2
- Python version: 2.7.11
- Operating System: Mac OS X
### Description:

pip freeze --requirement doesn't accept inline comments
### What I've run:

```
pip freeze -r requirements.txt
```

Output:

```
Invalid requirement: 'alembic==0.8.6                          # MIT license'
Traceback (most recent call last):
  File ".../site-packages/pip/req/req_install.py", line 78, in __init__
    req = Requirement(req)
  File ".../site-packages/pip/_vendor/packaging/requirements.py", line 96, in __init__
    requirement_string[e.loc:e.loc + 8]))
InvalidRequirement: Invalid requirement, parse error at "'# MIT li'"
```

requirements.txt:

```
alembic==0.8.6                          # MIT license
Babel==2.3.4                            # BSD license
```

`pip install -r` works for this requirements.txt file.

Documentation states:

> Whitespace followed by a # causes the # and the remainder of the line to be treated as a comment.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pip/operations/freeze.py`
Content:
```
1 from __future__ import absolute_import
2 
3 import logging
4 import re
5 
6 import pip
7 from pip.req import InstallRequirement
8 from pip.utils import get_installed_distributions
9 from pip._vendor import pkg_resources
10 from pip._vendor.packaging.utils import canonicalize_name
11 from pip._vendor.pkg_resources import RequirementParseError
12 
13 
14 logger = logging.getLogger(__name__)
15 
16 
17 def freeze(
18         requirement=None,
19         find_links=None, local_only=None, user_only=None, skip_regex=None,
20         default_vcs=None,
21         isolated=False,
22         wheel_cache=None,
23         skip=()):
24     find_links = find_links or []
25     skip_match = None
26 
27     if skip_regex:
28         skip_match = re.compile(skip_regex).search
29 
30     dependency_links = []
31 
32     for dist in pkg_resources.working_set:
33         if dist.has_metadata('dependency_links.txt'):
34             dependency_links.extend(
35                 dist.get_metadata_lines('dependency_links.txt')
36             )
37     for link in find_links:
38         if '#egg=' in link:
39             dependency_links.append(link)
40     for link in find_links:
41         yield '-f %s' % link
42     installations = {}
43     for dist in get_installed_distributions(local_only=local_only,
44                                             skip=(),
45                                             user_only=user_only):
46         try:
47             req = pip.FrozenRequirement.from_dist(
48                 dist,
49                 dependency_links
50             )
51         except RequirementParseError:
52             logger.warning(
53                 "Could not parse requirement: %s",
54                 dist.project_name
55             )
56             continue
57         installations[req.name] = req
58 
59     if requirement:
60         # the options that don't get turned into an InstallRequirement
61         # should only be emitted once, even if the same option is in multiple
62         # requirements files, so we need to keep track of what has been emitted
63         # so that we don't emit it again if it's seen again
64         emitted_options = set()
65         for req_file_path in requirement:
66             with open(req_file_path) as req_file:
67                 for line in req_file:
68                     if (not line.strip() or
69                             line.strip().startswith('#') or
70                             (skip_match and skip_match(line)) or
71                             line.startswith((
72                                 '-r', '--requirement',
73                                 '-Z', '--always-unzip',
74                                 '-f', '--find-links',
75                                 '-i', '--index-url',
76                                 '--pre',
77                                 '--trusted-host',
78                                 '--process-dependency-links',
79                                 '--extra-index-url'))):
80                         line = line.rstrip()
81                         if line not in emitted_options:
82                             emitted_options.add(line)
83                             yield line
84                         continue
85 
86                     if line.startswith('-e') or line.startswith('--editable'):
87                         if line.startswith('-e'):
88                             line = line[2:].strip()
89                         else:
90                             line = line[len('--editable'):].strip().lstrip('=')
91                         line_req = InstallRequirement.from_editable(
92                             line,
93                             default_vcs=default_vcs,
94                             isolated=isolated,
95                             wheel_cache=wheel_cache,
96                         )
97                     else:
98                         line_req = InstallRequirement.from_line(
99                             line,
100                             isolated=isolated,
101                             wheel_cache=wheel_cache,
102                         )
103 
104                     if not line_req.name:
105                         logger.info(
106                             "Skipping line in requirement file [%s] because "
107                             "it's not clear what it would install: %s",
108                             req_file_path, line.strip(),
109                         )
110                         logger.info(
111                             "  (add #egg=PackageName to the URL to avoid"
112                             " this warning)"
113                         )
114                     elif line_req.name not in installations:
115                         logger.warning(
116                             "Requirement file [%s] contains %s, but that "
117                             "package is not installed",
118                             req_file_path, line.strip(),
119                         )
120                     else:
121                         yield str(installations[line_req.name]).rstrip()
122                         del installations[line_req.name]
123 
124         yield(
125             '## The following requirements were added by '
126             'pip freeze:'
127         )
128     for installation in sorted(
129             installations.values(), key=lambda x: x.name.lower()):
130         if canonicalize_name(installation.name) not in skip:
131             yield str(installation).rstrip()
132
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pip/operations/freeze.py b/pip/operations/freeze.py
--- a/pip/operations/freeze.py
+++ b/pip/operations/freeze.py
@@ -5,6 +5,7 @@
 
 import pip
 from pip.req import InstallRequirement
+from pip.req.req_file import COMMENT_RE
 from pip.utils import get_installed_distributions
 from pip._vendor import pkg_resources
 from pip._vendor.packaging.utils import canonicalize_name
@@ -96,7 +97,7 @@
                         )
                     else:
                         line_req = InstallRequirement.from_line(
-                            line,
+                            COMMENT_RE.sub('', line).strip(),
                             isolated=isolated,
                             wheel_cache=wheel_cache,
                         )
@@ -115,7 +116,7 @@
                         logger.warning(
                             "Requirement file [%s] contains %s, but that "
                             "package is not installed",
-                            req_file_path, line.strip(),
+                            req_file_path, COMMENT_RE.sub('', line).strip(),
                         )
                     else:
                         yield str(installations[line_req.name]).rstrip()

{"golden_diff": "diff --git a/pip/operations/freeze.py b/pip/operations/freeze.py\n--- a/pip/operations/freeze.py\n+++ b/pip/operations/freeze.py\n@@ -5,6 +5,7 @@\n \n import pip\n from pip.req import InstallRequirement\n+from pip.req.req_file import COMMENT_RE\n from pip.utils import get_installed_distributions\n from pip._vendor import pkg_resources\n from pip._vendor.packaging.utils import canonicalize_name\n@@ -96,7 +97,7 @@\n                         )\n                     else:\n                         line_req = InstallRequirement.from_line(\n-                            line,\n+                            COMMENT_RE.sub('', line).strip(),\n                             isolated=isolated,\n                             wheel_cache=wheel_cache,\n                         )\n@@ -115,7 +116,7 @@\n                         logger.warning(\n                             \"Requirement file [%s] contains %s, but that \"\n                             \"package is not installed\",\n-                            req_file_path, line.strip(),\n+                            req_file_path, COMMENT_RE.sub('', line).strip(),\n                         )\n                     else:\n                         yield str(installations[line_req.name]).rstrip()\n", "issue": "pip freeze --requirement doesn't accept inline comments\n- Pip version: 8.1.2\n- Python version: 2.7.11\n- Operating System: Mac OS X\n### Description:\n\npip freeze --requirement doesn't accept inline comments\n### What I've run:\n\n```\npip freeze -r requirements.txt\n```\n\nOutput:\n\n```\nInvalid requirement: 'alembic==0.8.6                          # MIT license'\nTraceback (most recent call last):\n  File \".../site-packages/pip/req/req_install.py\", line 78, in __init__\n    req = Requirement(req)\n  File \".../site-packages/pip/_vendor/packaging/requirements.py\", line 96, in __init__\n    requirement_string[e.loc:e.loc + 8]))\nInvalidRequirement: Invalid requirement, parse error at \"'# MIT li'\"\n```\n\nrequirements.txt:\n\n```\nalembic==0.8.6                          # MIT license\nBabel==2.3.4                            # BSD license\n```\n\n`pip install -r` works for this requirements.txt file.\n\nDocumentation states:\n\n> Whitespace followed by a # causes the # and the remainder of the line to be treated as a comment.\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nimport logging\nimport re\n\nimport pip\nfrom pip.req import InstallRequirement\nfrom pip.utils import get_installed_distributions\nfrom pip._vendor import pkg_resources\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.pkg_resources import RequirementParseError\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef freeze(\n        requirement=None,\n        find_links=None, local_only=None, user_only=None, skip_regex=None,\n        default_vcs=None,\n        isolated=False,\n        wheel_cache=None,\n        skip=()):\n    find_links = find_links or []\n    skip_match = None\n\n    if skip_regex:\n        skip_match = re.compile(skip_regex).search\n\n    dependency_links = []\n\n    for dist in pkg_resources.working_set:\n        if dist.has_metadata('dependency_links.txt'):\n            dependency_links.extend(\n                dist.get_metadata_lines('dependency_links.txt')\n            )\n    for link in find_links:\n        if '#egg=' in link:\n            dependency_links.append(link)\n    for link in find_links:\n        yield '-f %s' % link\n    installations = {}\n    for dist in get_installed_distributions(local_only=local_only,\n                                            skip=(),\n                                            user_only=user_only):\n        try:\n            req = pip.FrozenRequirement.from_dist(\n                dist,\n                dependency_links\n            )\n        except RequirementParseError:\n            logger.warning(\n                \"Could not parse requirement: %s\",\n                dist.project_name\n            )\n            continue\n        installations[req.name] = req\n\n    if requirement:\n        # the options that don't get turned into an InstallRequirement\n        # should only be emitted once, even if the same option is in multiple\n        # requirements files, so we need to keep track of what has been emitted\n        # so that we don't emit it again if it's seen again\n        emitted_options = set()\n        for req_file_path in requirement:\n            with open(req_file_path) as req_file:\n                for line in req_file:\n                    if (not line.strip() or\n                            line.strip().startswith('#') or\n                            (skip_match and skip_match(line)) or\n                            line.startswith((\n                                '-r', '--requirement',\n                                '-Z', '--always-unzip',\n                                '-f', '--find-links',\n                                '-i', '--index-url',\n                                '--pre',\n                                '--trusted-host',\n                                '--process-dependency-links',\n                                '--extra-index-url'))):\n                        line = line.rstrip()\n                        if line not in emitted_options:\n                            emitted_options.add(line)\n                            yield line\n                        continue\n\n                    if line.startswith('-e') or line.startswith('--editable'):\n                        if line.startswith('-e'):\n                            line = line[2:].strip()\n                        else:\n                            line = line[len('--editable'):].strip().lstrip('=')\n                        line_req = InstallRequirement.from_editable(\n                            line,\n                            default_vcs=default_vcs,\n                            isolated=isolated,\n                            wheel_cache=wheel_cache,\n                        )\n                    else:\n                        line_req = InstallRequirement.from_line(\n                            line,\n                            isolated=isolated,\n                            wheel_cache=wheel_cache,\n                        )\n\n                    if not line_req.name:\n                        logger.info(\n                            \"Skipping line in requirement file [%s] because \"\n                            \"it's not clear what it would install: %s\",\n                            req_file_path, line.strip(),\n                        )\n                        logger.info(\n                            \"  (add #egg=PackageName to the URL to avoid\"\n                            \" this warning)\"\n                        )\n                    elif line_req.name not in installations:\n                        logger.warning(\n                            \"Requirement file [%s] contains %s, but that \"\n                            \"package is not installed\",\n                            req_file_path, line.strip(),\n                        )\n                    else:\n                        yield str(installations[line_req.name]).rstrip()\n                        del installations[line_req.name]\n\n        yield(\n            '## The following requirements were added by '\n            'pip freeze:'\n        )\n    for installation in sorted(\n            installations.values(), key=lambda x: x.name.lower()):\n        if canonicalize_name(installation.name) not in skip:\n            yield str(installation).rstrip()\n", "path": "pip/operations/freeze.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nimport logging\nimport re\n\nimport pip\nfrom pip.req import InstallRequirement\nfrom pip.req.req_file import COMMENT_RE\nfrom pip.utils import get_installed_distributions\nfrom pip._vendor import pkg_resources\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.pkg_resources import RequirementParseError\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef freeze(\n        requirement=None,\n        find_links=None, local_only=None, user_only=None, skip_regex=None,\n        default_vcs=None,\n        isolated=False,\n        wheel_cache=None,\n        skip=()):\n    find_links = find_links or []\n    skip_match = None\n\n    if skip_regex:\n        skip_match = re.compile(skip_regex).search\n\n    dependency_links = []\n\n    for dist in pkg_resources.working_set:\n        if dist.has_metadata('dependency_links.txt'):\n            dependency_links.extend(\n                dist.get_metadata_lines('dependency_links.txt')\n            )\n    for link in find_links:\n        if '#egg=' in link:\n            dependency_links.append(link)\n    for link in find_links:\n        yield '-f %s' % link\n    installations = {}\n    for dist in get_installed_distributions(local_only=local_only,\n                                            skip=(),\n                                            user_only=user_only):\n        try:\n            req = pip.FrozenRequirement.from_dist(\n                dist,\n                dependency_links\n            )\n        except RequirementParseError:\n            logger.warning(\n                \"Could not parse requirement: %s\",\n                dist.project_name\n            )\n            continue\n        installations[req.name] = req\n\n    if requirement:\n        # the options that don't get turned into an InstallRequirement\n        # should only be emitted once, even if the same option is in multiple\n        # requirements files, so we need to keep track of what has been emitted\n        # so that we don't emit it again if it's seen again\n        emitted_options = set()\n        for req_file_path in requirement:\n            with open(req_file_path) as req_file:\n                for line in req_file:\n                    if (not line.strip() or\n                            line.strip().startswith('#') or\n                            (skip_match and skip_match(line)) or\n                            line.startswith((\n                                '-r', '--requirement',\n                                '-Z', '--always-unzip',\n                                '-f', '--find-links',\n                                '-i', '--index-url',\n                                '--pre',\n                                '--trusted-host',\n                                '--process-dependency-links',\n                                '--extra-index-url'))):\n                        line = line.rstrip()\n                        if line not in emitted_options:\n                            emitted_options.add(line)\n                            yield line\n                        continue\n\n                    if line.startswith('-e') or line.startswith('--editable'):\n                        if line.startswith('-e'):\n                            line = line[2:].strip()\n                        else:\n                            line = line[len('--editable'):].strip().lstrip('=')\n                        line_req = InstallRequirement.from_editable(\n                            line,\n                            default_vcs=default_vcs,\n                            isolated=isolated,\n                            wheel_cache=wheel_cache,\n                        )\n                    else:\n                        line_req = InstallRequirement.from_line(\n                            COMMENT_RE.sub('', line).strip(),\n                            isolated=isolated,\n                            wheel_cache=wheel_cache,\n                        )\n\n                    if not line_req.name:\n                        logger.info(\n                            \"Skipping line in requirement file [%s] because \"\n                            \"it's not clear what it would install: %s\",\n                            req_file_path, line.strip(),\n                        )\n                        logger.info(\n                            \"  (add #egg=PackageName to the URL to avoid\"\n                            \" this warning)\"\n                        )\n                    elif line_req.name not in installations:\n                        logger.warning(\n                            \"Requirement file [%s] contains %s, but that \"\n                            \"package is not installed\",\n                            req_file_path, COMMENT_RE.sub('', line).strip(),\n                        )\n                    else:\n                        yield str(installations[line_req.name]).rstrip()\n                        del installations[line_req.name]\n\n        yield(\n            '## The following requirements were added by '\n            'pip freeze:'\n        )\n    for installation in sorted(\n            installations.values(), key=lambda x: x.name.lower()):\n        if canonicalize_name(installation.name) not in skip:\n            yield str(installation).rstrip()\n", "path": "pip/operations/freeze.py"}]}