poetry-dotenv-plugin icon indicating copy to clipboard operation
poetry-dotenv-plugin copied to clipboard

Utelize the poetry shell command

Open MaKaNu opened this issue 1 year ago • 2 comments

I recognized, that my Variables are available with poetry run. But if I use poetry shell the variables are still using the variables I specified global.

poetry shell should also override the variables.

MaKaNu avatar Feb 15 '24 09:02 MaKaNu

@MaKaNu After try a lot, I found that poetry shell was able to override variables in Windows.

Bash/Zsh/Fish in ubuntu/centos/MacOS are able to reproduce, this is because poetry-dotenv-plugin set variables into os.environ before virtual environment activated, and poetry activate virtual environment by pexpect.spawn which will run the shell initial file (such as: .bashrc/.zshrc/.profile) that specified global variables again.

One solution is to send export command into interactive environment:

# Add the following lines to `~/.local/share/pipx/venvs/poetry/lib/python3.10/site-packages/poetry/utils/shell.py`
        import dotenv
        if variables := dotenv.dotenv_values(Path.cwd()/'.env').items():
            export_cmd = ' && '.join(f'export {k}={v!r}' for k, v in variables)
            c.sendline(export_cmd)
image

waketzheng avatar Jul 19 '24 10:07 waketzheng

Or use source .env:

        import dotenv
        path = os.environ.get("POETRY_DOTENV_LOCATION") or dotenv.find_dotenv(usecwd=True)
        if dotenv.dotenv_values(path):
            c.sendline(f"source {path}")

waketzheng avatar Jul 22 '24 14:07 waketzheng