使用子进程激活 conda 环境

Activate conda environment using subprocess

我正在尝试查找 pandas 的版本:

def check_library_version():
    print("Checking library version")
    subprocess.run(f'bash -c "conda activate {ENV_NAME};"', shell=True)
    import pandas
    pandas.__version__

期望的输出: 1.1.3

输出:

Checking library version

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'. To initialize your shell, run

$ conda init <SHELL_NAME>

Currently supported shells are:

  • bash
  • fish
  • tcsh
  • xonsh
  • zsh
  • powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

澄清一下,我不打算更新当前 运行 脚本的环境;我只是想简单地激活那个环境并找出那里安装了哪个 Pandas 版本。

这根本没有任何意义;您激活的 Conda 环境在子进程终止时终止。

您应该(conda init 和)conda activate 您的虚拟环境 您 运行 任何 Python 代码之前。

如果您只想激活,运行 一个简单的 Python 脚本作为当前 Python 的子进程,然后在虚拟环境之外继续执行当前脚本,试试像

subprocess.run(f"""conda init bash
    conda activate {ENV_NAME}
    python -c 'import pandas; print(pandas.__version__)'""",
    shell=True, executable='/bin/bash', check=True)

这只是将输出打印给用户;如果您的 Python 程序想要接收它,您需要添加正确的标志;

check = subprocess.run(...whatever..., text=True, capture_output=True)
pandas_version = check.stdout

(不幸的是没有 conda init sh;我认为上面的任何内容都不依赖于 executable='/bin/bash' 否则。也许有一种方法可以 运行 POSIX sh 并删除 Bash 要求。)