Last active
June 21, 2024 21:13
-
-
Save tijsmaas/00bf6aa4fa02e4f9a7e41f5ac2c26cff to your computer and use it in GitHub Desktop.
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 | |
parser = argparse.ArgumentParser(description='(anaconda) environment.yml -> (pip) requirements.txt') | |
parser.add_argument('environment_yml_file', 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() | |
basepath = args.environment_yml_file.replace("\\",'/').rsplit('/', maxsplit=1)[0] | |
out_file = args.o | |
if out_file == None: | |
out_file = basepath + '/' + 'requirements.txt' | |
print(args.environment_yml_file, '->', out_file) | |
yaml = ruamel.yaml.YAML() | |
data = yaml.load(open(args.environment_yml_file)) | |
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) |
python3 -m pip install ruamel.yaml
python3 convert_enrivonment_yml_to_requirements.py ./environment.yml
python3 -m pip install ruamel.yaml
#Save the yml2requirements.py and environment.yml in same folder and CD to it! Create an empty requirements.txt file in the smae folder.
python3 yml2requirements.py environment.yml -o requirements.txt
@tijsmaas Thanks for the updated version of the script! 🙏
Moreover:
- ruamel.yaml needs to be installed before using the script using
python3 -m pip install ruamel.yaml
. - Regarding the usage, the input file must include the absolute or relative path), so that the output file can be properly created.
Ex:python3 convert_conda_env_to_pip_reqs.py ./conda_environment.yml
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
python3 -m pip install ruamel.yml