Skip to content

Instantly share code, notes, and snippets.

@tijsmaas
Last active November 21, 2023 05:26
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tijsmaas/00bf6aa4fa02e4f9a7e41f5ac2c26cff to your computer and use it in GitHub Desktop.
Save tijsmaas/00bf6aa4fa02e4f9a7e41f5ac2c26cff to your computer and use it in GitHub Desktop.
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)
@miroslavradojevic
Copy link

python3 -m pip install ruamel.yml

@maxerbubba
Copy link

maxerbubba commented Jan 23, 2021

python3 -m pip install ruamel.yaml
python3 convert_enrivonment_yml_to_requirements.py ./environment.yml

@sumodnandanwar
Copy link

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

@dxps
Copy link

dxps commented Jul 21, 2023

@tijsmaas Thanks for the updated version of the script! 🙏
Moreover:

  1. ruamel.yaml needs to be installed before using the script using python3 -m pip install ruamel.yaml.
  2. 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