diff --git a/Lib/test/test_venv.py b/Lib/test/test_venv.py index 678615ea172aefa..33975bf00de46ab 100644 --- a/Lib/test/test_venv.py +++ b/Lib/test/test_venv.py @@ -1075,6 +1075,19 @@ def test_pathsep_error(self): self.assertRaises(ValueError, venv.create, bad_itempath) self.assertRaises(ValueError, venv.create, FakePath(bad_itempath)) + def test_line_break_error(self): + """ + Test that venv creation fails when the target directory contains + a line break. + """ + rmtree(self.env_dir) + for line_break in '\n', '\r': + with self.subTest(line_break=line_break): + bad_itempath = f'{self.env_dir}{line_break}x' + self.assertRaises(ValueError, venv.create, bad_itempath) + self.assertRaises(ValueError, venv.create, + FakePath(bad_itempath)) + @unittest.skipIf(os.name == 'nt', 'not relevant on Windows') @requireVenvCreate def test_zippath_from_non_installed_posix(self): diff --git a/Lib/venv/__init__.py b/Lib/venv/__init__.py index 620168be16862ec..364150b59538b41 100644 --- a/Lib/venv/__init__.py +++ b/Lib/venv/__init__.py @@ -149,6 +149,9 @@ def create_if_needed(d): if os.pathsep in os.fspath(env_dir): raise ValueError(f'Refusing to create a venv in {env_dir} because ' f'it contains the PATH separator {os.pathsep}.') + if '\n' in os.fspath(env_dir) or '\r' in os.fspath(env_dir): + raise ValueError(f'Refusing to create a venv in {env_dir!r} ' + 'because its path contains a line break.') if os.path.exists(env_dir) and self.clear: self.clear_directory(env_dir) context = types.SimpleNamespace() @@ -251,7 +254,8 @@ def create_configuration(self, context): if self.upgrade_deps: args.append('--upgrade-deps') if self.orig_prompt is not None: - args.append(f'--prompt="{self.orig_prompt}"') + prompt = self.orig_prompt.replace('\n', ' ').replace('\r', ' ') + args.append(f'--prompt="{prompt}"') if not self.scm_ignore_files: args.append('--without-scm-ignore-files') diff --git a/Misc/NEWS.d/next/Library/2026-10-30-09-59-22.gh-issue-160782.fN0HIu.rst b/Misc/NEWS.d/next/Library/2026-10-30-09-59-22.gh-issue-160782.fN0HIu.rst new file mode 100644 index 000000000000000..5a37c87a934b5a3 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-30-09-59-22.gh-issue-160782.fN0HIu.rst @@ -0,0 +1,2 @@ +:mod:`venv`: a line break in the prompt or the path no longer starts a new +line in ``pyvenv.cfg``; such a path now raises :exc:`ValueError`.