0

Background
I am trying to install new python virtual environment from python script. I can be able to install the fresh virtual environment, but fails to activate it. Here is my code.

def install_fresh_env() -> None:
    """Install fresh env."""
    # el-env is not exists. Uninstall it first
    env_name = "el-env"
    cmd = f"pyenv uninstall -f {env_name}"
    returned_value = subprocess.call(cmd, shell=True)
    print(returned_value)
    if returned_value in [1, 0]:
        # It does not exist which is good. Then create it.
        cmd_create_pyenv = "pyenv virtualenv 3.10.8 el-env"
        _ = subprocess.call(cmd_create_pyenv, shell=True)

    init_cmd = 'pyenv init -'
    virtual_init = 'pyenv virtualenv-init -'
    _ = subprocess.call(init_cmd, shell=True)
    __ = subprocess.call(virtual_init, shell=True)

    select_env_cmd = f"pyenv local {env_name}"
    _ = subprocess.call(select_env_cmd, shell=True)

    select_env_cmd = f"pyenv activate {env_name}"
    _ = subprocess.call(select_env_cmd, shell=True)

    check_cmd = "pyenv versions"
    _ = subprocess.call(check_cmd, shell=True)

The error messasges:

Failed to activate virtualenv.

Perhaps pyenv-virtualenv has not been loaded into your shell properly.
Please restart current shell and try again.

I have follow this Failed to activate virtualenv with pyenv. But it does not work.

Question:
How to activate virtual environment from python script?

joe
  • 8,383
  • 13
  • 61
  • 109

0 Answers0