使用子进程激活 conda 环境 [英] Activate conda environment using subprocess

查看:62
本文介绍了使用子进程激活 conda 环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找熊猫版本:

I am trying to find version of 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

Desired output: 1.1.3

输出:

检查库版本

CommandNotFoundError:您的 shell 尚未正确配置为使用畅达激活".要初始化您的 shell,请运行

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

$ conda init <SHELL_NAME>

目前支持的外壳有:

  • 重击
  • tcsh
  • xonsh
  • zsh
  • powershell

有关更多信息和选项,请参阅conda init --help".

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

重要提示:您可能需要在运行后关闭并重新启动 shell'康达初始化'.

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

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

To clarify, I don't seek to update the environment of the currently running script; I just want to briefly activate that environment and find out which Pandas version is installed there.

推荐答案

这根本没有任何意义;当子进程终止时,您激活的 Conda 环境也将终止.

This doesn't make any sense at all; the Conda environment you activated is terminated when the subprocess terminates.

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

You should (conda init and) conda activate your virtual environment before you run any Python code.

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

If you just want to activate, run a simple Python script as a subprocess of your current Python, and then proceed with the current script outside of the virtual environment, try something like

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 程序想要接收它,你需要添加正确的标志;

This just prints the output to the user; if your Python program wants to receive it, you need to add the correct flags;

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

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

(It is unfortunate that there is no conda init sh; I don't think anything in the above depends on executable='/bin/bash' otherwise. Perhaps there is a way to run this in POSIX sh and drop the Bash requirement.)

这篇关于使用子进程激活 conda 环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆