diff --git a/src/poetry/console/commands/init.py b/src/poetry/console/commands/init.py
index 329afc4d374..48698365e74 100644
--- a/src/poetry/console/commands/init.py
+++ b/src/poetry/console/commands/init.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-import sys
-
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
@@ -74,8 +72,9 @@ def handle(self) -> int:
from poetry.core.pyproject.toml import PyProjectTOML
from poetry.core.vcs.git import GitConfig
+ from poetry.config.config import Config
from poetry.layouts import layout
- from poetry.utils.env import SystemEnv
+ from poetry.utils.env import EnvManager
project_path = Path.cwd()
@@ -157,10 +156,15 @@ def handle(self) -> int:
python = self.option("python")
if not python:
- current_env = SystemEnv(Path(sys.executable))
+ config = Config.create()
default_python = "^" + ".".join(
- str(v) for v in current_env.version_info[:2]
+ str(v)
+ for v in EnvManager.get_python_version(
+ prefer_active_python=config.get("virtualenvs.prefer-active-python"),
+ io=self.io,
+ )[:2]
)
+
question = self.create_question(
f"Compatible Python versions [{default_python}]: ",
default=default_python,
diff --git a/tests/console/commands/test_init.py b/tests/console/commands/test_init.py
index 935e58e636e..ca88dcc7ba5 100644
--- a/tests/console/commands/test_init.py
+++ b/tests/console/commands/test_init.py
@@ -2,10 +2,12 @@
import os
import shutil
+import subprocess
import sys
from pathlib import Path
from typing import TYPE_CHECKING
+from typing import Any
import pytest
@@ -26,6 +28,7 @@
from poetry.core.packages.package import Package
from pytest_mock import MockerFixture
+ from poetry.config.config import Config
from poetry.poetry import Poetry
from tests.helpers import TestRepository
from tests.types import FixtureDirGetter
@@ -1057,3 +1060,46 @@ def test_package_include(
f'python = "^3.10"\n'
)
assert expected in tester.io.fetch_output()
+
+
+@pytest.mark.parametrize(
+ ["prefer_active", "python"],
+ [
+ (True, "1.1"),
+ (False, f"{sys.version_info[0]}.{sys.version_info[1]}"),
+ ],
+)
+def test_respect_prefer_active_on_init(
+ prefer_active: bool,
+ python: str,
+ config: Config,
+ mocker: MockerFixture,
+ tester: CommandTester,
+ source_dir: Path,
+):
+ from poetry.utils.env import GET_PYTHON_VERSION_ONELINER
+
+ orig_check_output = subprocess.check_output
+
+ def mock_check_output(cmd: str, *_: Any, **__: Any) -> str:
+ if GET_PYTHON_VERSION_ONELINER in cmd:
+ return "1.1.1"
+
+ return orig_check_output(cmd, *_, **__)
+
+ mocker.patch("subprocess.check_output", side_effect=mock_check_output)
+
+ config.config["virtualenvs"]["prefer-active-python"] = prefer_active
+ pyproject_file = source_dir / "pyproject.toml"
+
+ tester.execute(
+ "--author 'Your Name ' --name 'my-package'",
+ interactive=False,
+ )
+
+ expected = f"""\
+[tool.poetry.dependencies]
+python = "^{python}"
+"""
+
+ assert expected in pyproject_file.read_text()