Skip to content Skip to sidebar Skip to footer

Activate Conda Environment Using Subprocess

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)

Solution 1:

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

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

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)

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

(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.)

Post a Comment for "Activate Conda Environment Using Subprocess"