Skip to content

Instantly share code, notes, and snippets.

@kaangiray26
Last active November 10, 2021 13:04
Show Gist options
  • Save kaangiray26/8917a13989d29279d69605fbb9d78aab to your computer and use it in GitHub Desktop.
Save kaangiray26/8917a13989d29279d69605fbb9d78aab to your computer and use it in GitHub Desktop.
Python Virtual Environments

Create the virtual environment

The parameter env indicates the name of the environment, you can use any name you like instead of using env.

python3 -m venv env

Activate the virtual environment

source env/bin/activate

Confirm you're in the environment

This should point to .../env/bin/python

which python

Convert environment.yml into requirements.txt for pip usage

Okay, this is wrong and stupid but it works. This is a One-Liner that reads environment.yml and converts it into a proper formatted dependency file for pip.

python -c "import base64; exec(base64.decodebytes(b'aW5kZXggPSBOb25lCmYgICAgID0gb3BlbigiZW52aXJvbm1lbnQueW1sIiwgInIiKS5yZWFkKCku\nc3BsaXRsaW5lcygpCgpmb3IgbGluZSBpbiBmOgogICAgaWYgbGluZS5zdGFydHN3aXRoKCdkZXBl\nbmRlbmNpZXMnKToKICAgICAgICBpbmRleCA9IGYuaW5kZXgobGluZSkrMQogICAgICAgIGJyZWFr\nCgppZiBpbmRleDoKICAgIHdpdGggb3BlbigicmVxdWlyZW1lbnRzLnR4dCIsICJ3IikgYXMgbzoK\nICAgICAgICBmb3IgbGluZSBpbiBmW2luZGV4Ol06CiAgICAgICAgICAgIG8ud3JpdGUoIiA9PSAi\nLmpvaW4obGluZS5zcGxpdCgiLSIpWy0xXS5zdHJpcCgpLnNwbGl0KCI9IilbOjJdKSArICJcbiIp\nCgpwcmludCgiZG9uZS4iKQ=='))"

Here's the content of that suspicious looking base64-encoded string:

index = None
f     = open("environment.yml", "r").read().splitlines()

for line in f:
    if line.startswith('dependencies'):
        index = f.index(line)+1
        break

if index:
    with open("requirements.txt", "w") as o:
        for line in f[index:]:
            o.write(" == ".join(line.split("-")[-1].strip().split("=")[:2]) + "\n")

print("done.")

Dectivate the virtual environment

deactivate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment