Skip to content

Virtualenv

virtualenv is a tool to create isolated Python environments.

How to install

Max OSX

Mac OSX에서 brew를 통해, 아래와 같이 설치할 수 있다.

$ brew update  
$ brew install pyenv-virtualenv

아래의 내용을 프로파일에 추가하면 완료된다.

if which pyenv-virtualenv-init > /dev/null; then eval "$(pyenv virtualenv-init -)"; fi

How to use

새로운 개발 환경(의존성 환경)을 만들고 싶을 경우 pyenv virtualenv {PYTHON_VERSION} {VIRTUAL_ENV_NAME}의 형태로 입력하면 된다.

아래와 같이 출력

yourui-MacBook-Pro:~ your$ pyenv virtualenv 2.7.11 your-pyenv-2.7.11
Collecting virtualenv
  Downloading virtualenv-15.0.1-py2.py3-none-any.whl (1.8MB)
    100% |████████████████████████████████| 1.8MB 235kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv-15.0.1
You are using pip version 7.1.2, however version 8.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
New python executable in /Users/your/.pyenv/versions/2.7.11/envs/your-pyenv-2.7.11/bin/python2.7
Also creating executable in /Users/your/.pyenv/versions/2.7.11/envs/your-pyenv-2.7.11/bin/python
Installing setuptools, pip, wheel...done.
Ignoring indexes: https://pypi.python.org/simple
Requirement already satisfied (use --upgrade to upgrade): setuptools in /Users/your/.pyenv/versions/2.7.11/envs/your-pyenv-2.7.11/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): pip in /Users/your/.pyenv/versions/2.7.11/envs/your-pyenv-2.7.11/lib/python2.7/site-packages

전부 만들어졌을 경우 아래와 pyenv를 사용하는 것과 같이 진행하면 된다.

yourui-MacBook-Pro:~ your$ pyenv versions
  system
* 2.7.11 (set by PYENV_VERSION environment variable)
  2.7.11/envs/your-pyenv-2.7.11
  your-pyenv-2.7.11

yourui-MacBook-Pro:~ your$ pyenv shell your-pyenv-2.7.11
pyenv-virtualenv: deactivate
pyenv-virtualenv: activate your-pyenv-2.7.11
pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior.

현재 적용된 환경정보를 확인하고 싶다면 아래와 같이 입력하면 된다.

$ virtualenv versions

가상환경의 Enable & Disable의 수동 적용은 아래의 명령으로 할 수 있다.

  • pyenv activate
  • pyenv deactivate

Install path

위의 설치 예제와 같이 환경이름을 your-pyenv-2.7.11로 적용했을 경우 Python 설치 경로는 아래와 같다.

/Users/your/.pyenv/versions/your-pyenv-2.7.11/

Tip

pyenv prompt display

현재 적용된 Python 환경정보가 프롬프트 좌측에 아래와 같이 출력된다.

(your-pyenv-2.7.11) yourui-MacBook-Pro:~ your$

이 것이 거슬린다면 아래와 같이 DISABLE할 수 있다.

export PYENV_VIRTUALENV_DISABLE_PROMPT=1

activate_this.py

Python 에서 격리하기 위한 실행 코드로 사용되는 파일:

# -*- coding: utf-8 -*-
"""Activate virtualenv for current interpreter:
Use exec(open(this_file).read(), {'__file__': this_file}).
This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.
"""
import os
import site
import sys

try:
    abs_file = os.path.abspath(__file__)
except NameError:
    raise AssertionError("You must use exec(open(this_file).read(), {'__file__': this_file}))")

bin_dir = os.path.dirname(abs_file)
base = bin_dir[: -len("__BIN_NAME__") - 1]  # strip away the bin part from the __file__, plus the path separator

# prepend bin to PATH (this file is inside the bin directory)
os.environ["PATH"] = os.pathsep.join([bin_dir] + os.environ.get("PATH", "").split(os.pathsep))
os.environ["VIRTUAL_ENV"] = base  # virtual env is right above bin directory

# add the virtual environments libraries to the host python import mechanism
prev_length = len(sys.path)
for lib in "__LIB_FOLDERS__".split(os.pathsep):
    path = os.path.realpath(os.path.join(bin_dir, lib))
    site.addsitedir(path.decode("utf-8") if "__DECODE_PATH__" else path)
sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]

sys.real_prefix = sys.prefix
sys.prefix = base

__BIN_NAME__, __LIB_FOLDERS__, __DECODE_PATH__는, 위 스크립트가 호출될 때 치환되는 영역이다.

Troubleshooting

prompt changing will be removed from future release

pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior.

간단히, pyenv-virtualenv의 환경이 바뀌어서 나타나는 현상. 바꾸지 말자.

Local Download

Pyenv-virtualenv-b952f57.tar.gz
Latest commit b952f57
Download: 2016-05-04

See also

  • pyenv: Python 버전 관리.
  • Virtualenv: Python 패키지 의존성 관리.
  • autoenv: 자동 환경(Environments) 설정.
  • venv: Python venv

Favorite site

References


  1. Pyenv_virtualenv_autoenv_-_Python_dev_env.pdf