Last active
November 4, 2020 10:59
-
-
Save miroslavradojevic/f73eec070b027a78e0d5c4eab2bc2841 to your computer and use it in GitHub Desktop.
Import anaconda environment .yml in virtualenv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ruamel.yaml | |
import argparse | |
from pathlib import Path | |
from os.path import exists | |
parser = argparse.ArgumentParser(description='(anaconda) environment.yml -> (pip) requirements.txt') | |
parser.add_argument('yml', type=str, metavar='environment.yml', default='environment.yml', help='the input file') | |
parser.add_argument('-o', type=str, metavar='requirements.txt', default=None, help='the output file') | |
args = parser.parse_args() | |
if not exists(args.yml): | |
print("{} does not exist\nexiting...".format(args.yml)) | |
exit() | |
path = Path(args.yml) | |
basepath = str(path.parent) | |
out_file = args.o | |
if out_file == None: | |
out_file = basepath + '/' + 'requirements.txt' | |
print(args.yml, '->', out_file) | |
yaml = ruamel.yaml.YAML() | |
data = yaml.load(open(args.yml)) | |
requirements = [] | |
for dep in data['dependencies']: | |
if isinstance(dep, str): | |
arr = dep.split('=') | |
package = arr[0] | |
package_version = arr[1] | |
if len(arr) == 3: | |
python_version = arr[2] | |
if python_version == '0': | |
continue | |
if package != 'python': | |
requirements.append(package + '==' + package_version) | |
elif isinstance(dep, dict): | |
for preq in dep.get('pip', []): | |
requirements.append(preq) | |
with open(out_file, 'w') as fp: | |
for requirement in requirements: | |
print(requirement, file=fp) | |
print("Intall dependencies within the right python environment using:") | |
print('pip install -r ' + out_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment