Created
January 26, 2021 08:02
-
-
Save tamamu/ac8dd8465f791c2e7e396246ad6e8a5b to your computer and use it in GitHub Desktop.
Generate Dockerfile from current Python environment
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 imp | |
import os.path | |
import sys | |
import types | |
import platform | |
__dockerfile_template__ = """ | |
FROM ubuntu:latest | |
ENV DEBIAN_FRONTEND=noninteractive | |
RUN apt-get update && apt-get -y update | |
RUN apt-get install -y build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl git | |
RUN useradd -m python_user | |
WORKDIR /home/python_user | |
USER python_user | |
RUN git clone https://github.com/pyenv/pyenv.git .pyenv | |
ENV HOME /home/python_user | |
ENV PYENV_ROOT $HOME/.pyenv | |
ENV PATH $PYENV_ROOT/shims:$PYENV_ROOT/bin:$PATH | |
RUN pyenv update && \ | |
pyenv install {version} && \ | |
pyenv global {version} | |
RUN pip install jupyter | |
RUN pip install {modules} | |
""" | |
def is_external_module(module_name): | |
python_path = os.path.dirname(sys.executable) | |
module_path = imp.find_module(module_name) | |
return module_path[1] != None and 'site-packages' in module_path[1] | |
def external_imports(): | |
names = set() | |
for name, val in globals().copy().items(): | |
if isinstance(val, types.ModuleType) and is_external_module(val.__name__): | |
names.add(val.__name__) | |
return names | |
def generate_dockerfile_from_current_environment(): | |
version = platform.python_version() | |
modules = ' '.join(external_imports()) | |
return __dockerfile_template__.format(version=version, modules=modules) | |
print(generate_dockerfile_from_current_environment()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment