I\'m looking for a good way to figure out the name of the conda environment I\'m in from within running code or an interactive python instance.
The use-case is that
Edit: Oops, I hadn't noticed Ivo's answer. Let's say that I am expanding a little bit on it.
If you run your python script from terminal:
import os
os.system("conda env list")
This will list all conda environments, as from terminal with conda env list
.
Slightly better:
import os
_ = os.system("conda env list | grep '*'")
The _ =
bit will silence the exist status of the call to os.system
(0
if successful), and grep
will only print out the line with the activated conda environment.
If you don't run your script from terminal (e.g. it is scheduled via crontab
), then the above won't have anywhere to "print" the result. Instead, you need to use something like python's subprocess
module. The simplest solution is probably to run:
import subprocess
output = subprocess.check_output("conda env list | grep '*'", shell=True, encoding='utf-8')
print(output)
Namely output
is a string containing the output of the command conda env list
, not its exit status (that too can be retrieved, see documentation of the subprocess
module).
Now that you have a string with the information on the activated conda environment, you can perform whichever test you need (using regular expressions) to perform (or not) the installs mentioned in your question.
Remark.
Of course, print(output)
in the block above will have no effect if your script is not run from terminal, but if you test the block in a script which you run from terminal, then you can verify that it gives you what you want. You can for instance print this information into a log file (using the logging
module is recommended).