Search code examples
pythonpackageversionpackage-managerspython-poetry

How can I specify which Python version poetry should create venv?


I started using Poetry recently. I really like straightforward package management, but I can’t seem to resolve one thing: The Python version it should use. I have Python 3.9 and 3.7 on my machine. 3.7 is higher in priority in system environmental variables - so that might be the reason of the issue.

But let’s get back to example. Part of my pyproject.toml file looks like this:

[tool.poetry.dependencies]
python = "3.9.2"
pandas = "^1.2.3"
requests = "^2.25.1"

I manually changed Python to 3.9.2, used poetry add to add Pandas and requests and then ran poetry install. I had virtualenvs.in-project set to true, so my virtual environment was created without any error in my project directory. However, when it is activated, I can see it is using Python 3.7.9 (on Windows, starting from a PowerShell window):

cd C:\pyprojects
c:/pyprojects/***/.venv/Scripts/Activate.ps1

(.venv) c:/pyprojects/***/.venv/Scripts/python.exe

Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

How can I explicitly tell Poetry to use the exact Python version if pyproject.toml python = "3.9.2" is not enough? Is it picking the first Python environmental variable, which in my case is python37? Or am I missing something here?


Solution

  • Poetry can't fully manage Python versions on its own using the version specified in the pyproject.toml. You can either use a tool like pyenv (or pyenv-win if you're using Windows) for managing multiple versions, or you can use poetry env use path/to/python. If Python 3.9 is in your path or available on your system via pyenv or some similar version management tool, you can use poetry env use python3.9 or poetry env use 3.9. You can read more about poetry env use here.