Skip to content

Instantly share code, notes, and snippets.

@joel-kelly
Created July 8, 2022 18:07
Show Gist options
  • Save joel-kelly/8ba25be161f5406a80de220adc1c6704 to your computer and use it in GitHub Desktop.
Save joel-kelly/8ba25be161f5406a80de220adc1c6704 to your computer and use it in GitHub Desktop.
Export all conda environments as yml files to a specified directory
import subprocess as sub
import re
import os
#modified from https://github.com/conda/conda/issues/5165
# create list of current environments
sub.check_call(" ".join(['conda','env','list','>','envs.txt']),shell=True)
# load and parse environment names
envs = {}
with open("envs.txt", 'r') as f:
lines = f.read().splitlines()
lines = [l.replace("*","") for l in lines] #get rid of asterix which denotes active environment
for line in lines[2:]:
line_match = re.findall(r'(\w*)\s+(C:.*)',line)
if line_match:
name,directory = line_match[0]
if not name:
local_name = directory.split("\\")[-1]
print(f"Environment {local_name} is not installed in default conda environment directory.")
print(f"The environment name will be appended with '_not_in_default_path'")
envs[f"{local_name}_not_in_default_path"] = directory
else:
envs[name] = directory
# write environment packages out
directory = "directory_location" #change to your preferred directory location
os.chdir(directory)
for env_name, direcotry in envs.items():
print("Backing up...",env_name)
if "_not_in_default_path" in env_name:
cmd = f"conda env export --no-build --p {directory} > {env_name}.yml"
else:
cmd = f"conda env export --no-build --name {env_name} > {env_name}.yml"
sub.check_call(cmd,shell=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment