Virtualenv

Co to je a jak to funguje?

PIP = instaluje cizí balíčky

Příklady předpokládají UNIX + Bash

Shebang = #!/usr/bin/env python

Než začneme..

Motivace

Python

$ python mujprogram.py

Evžen

Python 2

Python 3

$ python2 mujprogram.py
$ python3 mujprogram.py
$ ./mujprogram.py

Python 3.4

Python 3.6

$ python3.4 mujprogram.py
$ python3.6 mujprogram.py
$ ./mujprogram.py

Externí balíčky

Python 3.6

click 3.2

click 5.1

$ cat mujprogram.py
>>> import click  # 3.2
>>> ...

$ python3 mujprogram.py
$ cat mujprogram-novy.py
>>> import click  # 5.1
>>> ...

$ python3 mujprogram-novy.py

Řešení

Python 3.6

Python 2.7

click 5.1

requests 2.18.4

click 4.0

venv-test

venv-mujprojekt

click 3.2

venv-backport

Jak na to?

$ python --version
Python 2.7.14

# vytvoření virtualenvu

$ python3.6 -m venv test

$ ls
test
# instalace clicku

$ test/bin/pip install click
Successfully installed click-6.7

$ ls
test

$ test/bin/pip freeze
click==6.7
# "napsání" programu

$ echo "import click" >> mujprogram.py

$ ls
mujprogram.py
test
$ test/bin/python --version
Python 3.6.4

# spuštění programu

$ test/bin/python mujprogram.py

aktivace / deaktivace

$ python --vesion
Python 2.7.14

# aktivace

$ source test/bin/activate

(test) $ python --version
Python 3.6.4
# co je nainstalováno?

(test) $ pip freeze
click==6.7

# spuštění programu

(test) $ python mujprogram.py
# deaktivace

(test) $ deactivate

# spuštění programu MIMO virtualenv

$ python mujprogram.py
# co se stane?

Jak to funguje?

workingenv (✝ 2007)

→ virtualenv (2007)

→ adopce PyPA (2011)

→ PEP 405 (2011)

→ Python 3.3 (2012)

Historie

$ python3 -m venv --without-pip test

# co je uvnitř?

$ ls test
bin
include  # prázdný
lib/python3.6/site-packages  # prázdný
pyvenv.cfg

$ ls test/bin
activate
activate.csh
activate.fish
python  # -> python3
python3  # -> /opt/local/bin/python3

Dokumentace modulu site:

If a file named pyvenv.cfg exists one directory above sys.executable,
sys.prefix and sys.exec_prefix are set to that directory and it is also checked for site-packages.

PEP 405:

Thus, a Python virtual environment in its simplest form would consist of nothing more than a copy or symlink of the Python binary accompanied by a pyvenv.cfg file and a site-packages directory.

Co je podstatné?

# jak funguje aktivace?

$ cat test/bin/activate
...
VIRTUAL_ENV="/somewhere/test"
export VIRTUAL_ENV
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH
...

Pipenv

# začátek projektu

$ pipenv install click
Creating a Pipfile...
Creating a virtualenv...
Installing `click`...
Adding `click` to Pipfile's [packages]...
Updating Pipfile.lock...

$ ls
mujprogram.py
Pipfile
Pipfile.lock
# spuštění programu

$ pipenv run python mujprogram.py

# "aktivace"

$ pipenv shell
Executing: source ~/.local/share/virtualenvs/ ⏎
  virtualenv-kxl5pyYG/bin/activate

(virtualenv-kxl5pyYG) $

heurekadevs.cz/ctvrty-fialovy

@heurekadevs

Tomáš Bedřich

@tbedrich

Made with Slides.com