pythonvirtualenvpython-poetry

How to create a brand new virtual environment or duplicate an existing one in poetry? (Multiple environment in a project)


I have a project and an existing virtual environment created with poetry (poetry install/init). So, as far as I know, the purpouse of a virtual environment is avoiding to modify the system base environment and the possibility of isolation (per project, per development, per system etc...).

How can I create another brand new environment for my project in poetry? How can I eventually duplicate and use an existing one?

I mean that the current one (activated) should be not involved in this (except for eventually copying it) because I want to test another set of dependencies and code.

I am aware of this:


Solution

  • Poetry seems to be bound to one virtualenv per python interpreter. Poetry is also bound to the pyproject.toml file and its path to generate a new environment.

    So there are 2 tricky solutions:

    1 - change your deps in the pyproject.toml and use another python version (installed for example with pyenv) and then:

    poetry env use X.Y
    

    poetry will create a new virtual environment but this is not exactly the same as changing just some project deps.

    2 - use another pyproject.toml from another path:

    mkdir env_test
    cp pyproject.toml env_test/pyproject.toml
    cd env_test
    nano pyproject.toml # edit your dependencies
    poetry install # creates a brand new virtual environment
    poetry shell
    # run your script with the new environment
    

    This will generate a new environment with just the asked dependencies changed. Both environments can be used at the same time. After the test, it is eventually possible to delete the new environment with the env command.