1import argparse
2import json
3import os
4import shutil
5import subprocess as sp
6
7# Args
8parser = argparse.ArgumentParser(description='Creates a conda environment from file for a given Python version.')
9parser.add_argument('-n', '--name', type=str, nargs=1,
10                    help='The name of the created Python environment')
11parser.add_argument('-p', '--python', type=str, nargs=1,
12                    help='The version of the created Python environment')
13parser.add_argument('conda_file', nargs='*',
14                    help='The file for the created Python environment')
15
16args = parser.parse_args()
17
18with open(args.conda_file[0], "r") as handle:
19    script = handle.read()
20
21tmp_file = "tmp_env.yaml"
22script = script.replace("- python", "- python {}*".format(args.python[0]))
23
24with open(tmp_file, "w") as handle:
25    handle.write(script)
26
27# Figure out conda path
28if "CONDA_EXE" in os.environ:
29    conda_path = os.environ["CONDA_EXE"]
30else:
31    conda_path = shutil.which("conda")
32
33print("CONDA ENV NAME  {}".format(args.name[0]))
34print("PYTHON VERSION  {}".format(args.python[0]))
35print("CONDA FILE NAME {}".format(args.conda_file[0]))
36print("CONDA path      {}".format(conda_path))
37
38sp.call("{} env create -n {} -f {}".format(conda_path, args.name[0], tmp_file), shell=True)
39os.unlink(tmp_file)
40