9

I'm converting a shell script to Python and I'm searching for a way to activate and deactivate a conda environment programmatically in Python. I've looked through the Conda code on Github and haven't been able to find a good solution.

I need the environment to be activated so that I can run multiple statements in it. For example:

source activate my_env
easy_install numpy 
backup_db
initialize_db
source deactivate 

I'm having no luck using subprocess. :-(

William Hill
  • 91
  • 1
  • 4
  • are you trying to activate the environment from within a Python script or as part of a bash script? – James Aug 22 '17 at 00:23
  • @James I'm trying to activate the environment with the Python script. – William Hill Aug 22 '17 at 05:53
  • 3
    If you are trying to have the script switch to a new environment and then continue execution, that is not possible as each environment is isolated. Each environment uses it's own kernel, so switching to a new environment necessitates starting up a new Python kernel which knows nothing about the previous computation in the script. – James Aug 22 '17 at 12:26

2 Answers2

1

A round-a-bout way of doing it, but couldn't you have python just call the script directly?

Refer to this question on how to do that

Run a .bat file using python code

tisaconundrum
  • 2,156
  • 2
  • 22
  • 37
  • That would probably be my fallback plan as I would still have to extract the function and the associated variables to a different file. Thanks for idea though. – William Hill Aug 22 '17 at 05:58
1

Linux. Was trying to create bash script to run python function from my app with test environment specifications.

#!/bin/bash

conda run -n test python -c 'from otp import Qod; Qod()';

If you have python script not in the same directory you can add sys.path absolute or relative. Planning to upgrade this script bash automation

EakzIT
  • 602
  • 5
  • 8