Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 38 additions & 24 deletions Lib/site.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,7 @@ def _venv(state):
if candidate_conf:
virtual_conf = candidate_conf
system_site = "true"
version, version_info = None, None
version, version_info, python_version = None, None, None
# Issue 25185: Use UTF-8, as that's what the venv module uses when
# writing the file.
with open(virtual_conf, encoding='utf-8') as f:
Expand All @@ -999,31 +999,45 @@ def _venv(state):
version = value
elif key == 'version_info':
version_info = value

for field_name, field_value in [
('version',version), ('version_info',version_info)
elif key == 'python-version':
python_version = value

for field_name, field_value, should_error in [
# Run the fatal check first.
('python_version', python_version, True),
('version',version, False),
('version_info',version_info, False),
]:
if field_value is not None:
try:
major, minor = map(int, field_value.split(".")[:2])
except (ValueError, AttributeError):
_warn(
f"Malformed {field_name} string in pyvenv.cfg: {field_value!r}",
RuntimeWarning,
if field_value is None:
continue
try:
major, minor = map(int, field_value.split(".")[:2])
except (ValueError, AttributeError):
_warn(
f"Malformed {field_name} string in pyvenv.cfg: {field_value!r}",
RuntimeWarning,
)
continue
if should_error:
if (major, minor) != sys.version_info[:2]:
raise RuntimeError(
f"This virtual environment was created for Python {major}.{minor}, "
f"but the current interpreter is Python "
f"{sys.version_info.major}.{sys.version_info.minor}. "
"Consider running `python -m venv --upgrade` to update the environment.",
)
else:
if (
major == sys.version_info.major
and minor != sys.version_info.minor
):
_warn(
f"This virtual environment was created for Python {major}.{minor}, "
f"but the current interpreter is Python "
f"{sys.version_info.major}.{sys.version_info.minor}. "
"Consider running `python -m venv --upgrade` to update the environment.",
RuntimeWarning,
)
break
elif (
major == sys.version_info.major
and minor != sys.version_info.minor
):
_warn(
f"This virtual environment was created for Python {major}.{minor}, "
f"but the current interpreter is Python "
f"{sys.version_info.major}.{sys.version_info.minor}. "
"Consider running `python -m venv --upgrade` to update the environment.",
RuntimeWarning,
)
break

if sys.prefix != site_prefix:
_warn(
Expand Down
50 changes: 46 additions & 4 deletions Lib/test/test_venv.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ def _check_output_of_default_create(self):
self.assertIn('home = %s' % path, data)
self.assertIn('executable = %s' %
os.path.realpath(sys.executable), data)
self.assertIn("python-version = %d.%d" % (sys.version_info.major,
sys.version_info.minor),
data)
copies = '' if os.name=='nt' else ' --copies'
cmd = (f'command = {sys.executable} -m venv{copies} --without-pip '
f'--without-scm-ignore-files {self.env_dir}')
Expand Down Expand Up @@ -310,6 +313,45 @@ def test_sysconfig(self):
out, err = check_output(cmd, encoding='utf-8')
self.assertEqual(out.strip(), expected, err)

@requireVenvCreate
def test_python_version_mismatch_error(self):
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir, with_pip=False)

corrct_version = f"{sys.version_info.major}.{sys.version_info.minor}"
wrong_version = f"{sys.version_info.major}.{sys.version_info.minor + 1}"

cfg_path = self.get_env_file("pyvenv.cfg")
with open(cfg_path, encoding="utf-8") as f:
cfg_content = f.read()

cfg_content = cfg_content.replace(
f"python-version = {corrct_version}",
f"python-version = {wrong_version}",
)

with open(cfg_path, "w", encoding="utf-8") as f:
f.write(cfg_content)

envpy = self.envpy(real_env_dir=True)

proc = subprocess.run(
[envpy, "-c", 'print("done")'],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHOME": ""},
)

self.assertNotEqual(proc.returncode, 0)
self.assertNotIn("done", proc.stdout)
self.assertIn("RuntimeError", proc.stderr)
self.assertIn(f"Python {wrong_version}", proc.stderr)
self.assertIn(
f"Python {sys.version_info.major}.{sys.version_info.minor}",
proc.stderr,
)
self.assertIn("Consider running `python -m venv --upgrade`", proc.stderr)

@requireVenvCreate
def test_version_mismatch_warning(self):
"""
Expand All @@ -327,7 +369,7 @@ def test_version_mismatch_warning(self):

new_version = f"{sys.version_info.major}.{wrong_minor}"
if 'version =' in cfg_content:
cfg_content = re.sub(r'version = \d+\.\d+', f'version = {new_version}', cfg_content)
cfg_content = re.sub(r'(?m)^version = \d+\.\d+', f'version = {new_version}', cfg_content)

cfg_content += f'\nversion_info = {new_version}\n'

Expand Down Expand Up @@ -419,7 +461,7 @@ def test_malformed_version_warning(self):

malformed_version = "not.a.version"
if 'version =' in cfg_content:
cfg_content = re.sub(r'version = .+', f'version = {malformed_version}', cfg_content)
cfg_content = re.sub(r'(?m)^version = .+', f'version = {malformed_version}', cfg_content)

with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)
Expand Down Expand Up @@ -480,7 +522,7 @@ def test_conflicting_version_fields(self):

version_wrong = f"{sys.version_info.major}.{wrong_minor}"
if 'version =' in cfg_content:
cfg_content = re.sub(r'version = \d+\.\d+', f'version = {version_wrong}', cfg_content)
cfg_content = re.sub(r'(?m)^version = \d+\.\d+', f'version = {version_wrong}', cfg_content)

version_info_wrong = f"{sys.version_info.major}.{wrong_minor + 1}"
cfg_content += f'\nversion_info = {version_info_wrong}\n'
Expand Down Expand Up @@ -516,7 +558,7 @@ def test_different_major_version_no_warning(self):
new_version = f"{different_major}.{sys.version_info.minor}"

if 'version =' in cfg_content:
cfg_content = re.sub(r'version = \d+\.\d+', f'version = {new_version}', cfg_content)
cfg_content = re.sub(r'(?m)^version = \d+\.\d+', f'version = {new_version}', cfg_content)
with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)

Expand Down
2 changes: 2 additions & 0 deletions Lib/venv/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ def create_configuration(self, context):
incl = 'false'
f.write('include-system-site-packages = %s\n' % incl)
f.write('version = %d.%d.%d\n' % sys.version_info[:3])
f.write('python-version = %d.%d\n' % (sys.version_info.major,
sys.version_info.minor))
if self.prompt is not None:
f.write(f'prompt = {self.prompt!r}\n')
f.write('executable = %s\n' % os.path.realpath(sys.executable))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Add a ``python-version`` key to ``pyvenv.cfg`` files created by :mod:`venv`.
This implements :pep:`838`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fail at startup when the ``python-version`` in a virtual
environment's ``pyvenv.cfg`` does not match the running interpreter.
Loading