기본 콘텐츠로 건너뛰기

[파이썬] 파이썬 여러 버전 설치하기; virtualenv 사용하기.

source: http://bhfsteve.blogspot.kr/2012/05/run-multiple-python-versions-on-your.html

파이썬 여러 버전 사용하기

파이썬 2.7은 기본적으로 설치되어 있다고 가정

steve@ubuntu64 ~ $ sudo add-apt-repository ppa:fkrull/deadsnakes

steve@ubuntu64 ~ $ sudo apt-get update

steve@ubuntu64 ~ $ sudo apt-get install python2.4 python2.5 python2.6

이제 2.4 2.5 2.6 2.7이 모두 설치된 상태가 된다. 이 상태에서 python이라고 치면 여전히 2.7이 켜진다.
왜냐하면 python은 심볼릭링크이며 python2.7을 가리키기 때문. 

steve@ubuntu64 ~ $ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

steve@ubuntu64 ~ $ ls -l /usr/bin/python*
lrwxrwxrwx 1 root root       9 Apr 17 13:20 /usr/bin/python -> python2.7
lrwxrwxrwx 1 root root       9 Apr 17 13:20 /usr/bin/python2 -> python2.7
-rwxr-xr-x 1 root root 1216520 May 21 12:13 /usr/bin/python2.4
-rwxr-xr-x 1 root root 1403624 May  3 00:17 /usr/bin/python2.5
-rwxr-xr-x 1 root root 2652056 May 12 08:43 /usr/bin/python2.6
-rwxr-xr-x 1 root root 2993560 Apr 20 19:37 /usr/bin/python2.7

따라서 2.5버전을 실행하려면 아래와 같이 명시적인 버전을 함께 쓰면 된다.

steve@ubuntu64 ~ $ python2.5
Python 2.5.6 (r256:88840, May  3 2012, 04:16:14) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 


내가 2.6을 주로 사용하고자 한다해도  python 심볼릭링크를 수정하지는 말자. 내부적인 의존성 문제를 일으킬 가능성이 있다.  (This is a point of interest.  I would not mess with the symbolic link.  Ubuntu runs python for many internal maintenance scripts and those scripts are expecting the python version that shipped with ubuntu.)

Use virtualenv to manage your python installations and package sets

So now that you have multiple versions of python on your system, how to manage them?  How do you keep packages installed for one version separate from packages installed for another.  What if you want to run one version of django for client X and a different version for client Y?

That's where virtualenv comes in.  If your a ruby programmer, this is analogous to rvm.  Virtualenv lets you manage the python versions and package installations separately for different projects or clients.

Installing virtualenv is simple

As always, you're just a single apt-get command away from having virtualenv ready to go:

steve@ubuntu64 ~ $ sudo apt-get install python-virtualenv

That it.  Virtualenv is ready to go now.

Quick example

Say your starting a new project for a client.  They are running python2.5 and want to use the mocks, nose and coverage packages for testing.  Here a walkthrough of how to use virtualenv to manage the project.

First, let's create a directory for the project:

steve@ubuntu64 ~ $ mkdir -p ~/dev/project1
steve@ubuntu64 ~ $ cd ~/dev/project1

Next, run virtualenv to create the environment for the project:


steve@ubuntu64 ~/dev/project1 $ virtualenv -p /usr/bin/python2.5 .env
Running virtualenv with interpreter /usr/bin/python2.5
New python executable in .env/bin/python2.5
Also creating executable in .env/bin/python
Installing distribute.............................................................................................................................................................................................done.
Installing pip...............done.
steve@ubuntu64 ~/dev/project1 $ 

This command tells virtualenv to create a .env directory and to place a copy of the 2.5version of python in it.  This copy of the 2.5 python is brand-spankin' new.  It doesn't have any packages (beyond the standard library) installed.  You will need to install them yourself.  Any packages that you install in this instance of python will not be available to main python installation or other virtualenv instances.

Before your can use this new copy, you need to activate it:


steve@ubuntu64 ~/dev/project1 $ source .env/bin/activate
(.env)steve@ubuntu64 ~/dev/project1 $

The activate script manipulates your path environment variable, placing the new python instance first in your path.  This makes is so that when you run python, it will use the version from your instance:


(.env)steve@ubuntu64 ~/dev/project1 $ which python
/home/steve/dev/project1/.env/bin/python
(.env)steve@ubuntu64 ~/dev/project1 $ python
Python 2.5.6 (r256:88840, May  3 2012, 04:16:14) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Also, notice that your prompt starts with (.env).  This tells you that you're running with the virtualenv instance activated.  To install packages in your instance, use the pipcommand:


(.env)steve@ubuntu64 ~/dev/project1 $ pip install mock nose coverage
Downloading/unpacking mock
  Downloading mock-0.8.0.tar.gz (749Kb): 749Kb downloaded
  Running setup.py egg_info for package mock
    warning: no files found matching '*.png' under directory 'docs'
    warning: no files found matching '*.css' under directory 'docs'
    warning: no files found matching '*.html' under directory 'docs'
    warning: no files found matching '*.js' under directory 'docs'
Downloading/unpacking nose
  Downloading nose-1.1.2.tar.gz (729Kb): 729Kb downloaded
  In the tar file /tmp/pip-dH_WYa-unpack/nose-1.1.2.tar.gz the member nose-1.1.2/doc/doc_tests/test_selector_plugin/support/tests/mymodule/my_function$py.class is invalid: 'filename None not found'
  In the tar file /tmp/pip-dH_WYa-unpack/nose-1.1.2.tar.gz the member nose-1.1.2/doc/doc_tests/test_restricted_plugin_options/restricted_plugin_options.rst.py3.patch is invalid: 'filename None not found'
  Running setup.py egg_info for package nose
Downloading/unpacking coverage  Downloading coverage-3.5.2.tar.gz (115Kb): 115Kb downloaded
  Running setup.py egg_info for package coverage
    no previously-included directories found matching 'test'Installing collected packages: mock, nose, coverage
  Running setup.py install for mock
    warning: no files found matching '*.png' under directory 'docs'
    warning: no files found matching '*.css' under directory 'docs'
    warning: no files found matching '*.html' under directory 'docs'
    warning: no files found matching '*.js' under directory 'docs'
  Running setup.py install for nose
    Installing nosetests script to /home/steve/dev/project1/.env/bin
    Installing nosetests-2.5 script to /home/steve/dev/project1/.env/bin
  Running setup.py install for coverage
    building 'coverage.tracer' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.5 -c coverage/tracer.c -o build/temp.linux-x86_64-2.5/coverage/tracer.o
    coverage/tracer.c:3:20: fatal error: Python.h: No such file or directory
    compilation terminated.
    **
    ** Couldn't install with extension module, trying without it...
    ** SystemExit: error: command 'gcc' failed with exit status 1
    **
    no previously-included directories found matching 'test'
    Installing coverage script to /home/steve/dev/project1/.env/bin
Successfully installed mock nose coverage
Cleaning up...
(.env)steve@ubuntu64 ~/dev/project1 $

To see that the packages have been installed, simply use them:




(.env)steve@ubuntu64 ~/dev/project1 $ python
Python 2.5.6 (r256:88840, May  3 2012, 04:16:14) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mock
>>> import nose
>>> import coverage
>>>

When you're done working on the project, deactivate it.  You can always come back later and activate it again.


(.env)steve@ubuntu64 ~/dev/project1 $ deactivate
steve@ubuntu64 ~/dev/project1 $


Notice that when you deactivate the environment, your packages are no longer available:


steve@ubuntu64 ~/dev/project1 $ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mock
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named mock
>>> import nose
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named nose
>>> import coverage
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named coverage
>>>

You can create as many virtualenv environments as you like.  I create one for each project that I work on.


Bonus material


To make life even easier, here's a couple additional things I do that you might find helpful!

First, once you've started to use virtualenv with some frequency, you start to get tired of downloading and installing the same packages over and over.  Pip has the ability to cache your downloaded packages for reuse.  To do that, you'll need to create a directory to store the download packages in:

steve@ubuntu64 ~ $ mkdir ~/.pip_download_cache

Then you'll need to set a variable to inform pip of the new directory.  Add the following to your .bashrc file:

export PIP_DOWNLOAD_CACHE=/home/steve/.pip_download_cache

Now when you do a pip install, it will keep the downloaded files in the ~/.pip_download_cache directory.  The next time you do a pip install of the same package, it will just use the copy from the directory instead of downloading it again.


Second, it can be tedious to always have to type 'source .env/bin/activate' every time you want to activate an environment.  Since I always put my virtual environments in a .env directory I can count on the command to activate always being the same.  So I create an alias for it.  I added the the following to my ~/.bash_aliases file:

alias activate='source .env/bin/activate'

Now once I cd into the projects directory, I simply type activate to activate my virtual environment.

댓글

이 블로그의 인기 게시물

[맞춤법] 안돼(o) vs 안되(x); 안돼요(o) 안되요(x); 안되지(o) vs 안돼지(x);

source:  http://k.daum.net/qna/view.html?qid=0FKVD&l_cid=Q&l_st=1 쉽게 구분하는 방법만 말씀드리겠습니다.   안돼요는 안되어요가 줄어든 말입니다. 예를 들어보겠습니다.   당신이 그러면 안되지. 당신이 그러면 안돼지.   첫번째 문장이 맞고 두번째 문장이 틀립니다. 두번째 문장을 '당신이 그러면 안되어지'로 바꾸면 말이 이상하지요. '안돼지'로 쓸 수 있는 것은 '안되어지'로 쓸 수 있는 것입니다.   요즘 사업이 잘 안(돼서 되서) 죄송합니다. '돼서'와 '되서' 가운데 어떤 것이 맞을까요? 사업이 잘 '안되어서'가 말이 되니까 '안돼서'가 맞습니다.   즉, 이 두가지를 쉽게 구분하는 방법은 '돼' 자리에 '되어'를 넣어봐서 말이 되면 '돼'고 말이 안되면 '되'를 쓰면 됩니다.   아니면   되 자리에 하를 넣어보고   돼 자리에 해를 넣어서 어색하지 않으면 그대로 쓰면 됩니다.   안되요는 안하요가 되니 틀린 말이고   안돼요는 안해요가 되니 맞는 말입니다.   결국 안돼요가 표준어입니다.

[인코딩] MS949부터 유니코드까지

UHC = Unified Hangul Code = 통합형 한글 코드 = ks_c_5601-1987 이는 MS사가 기존 한글 2,350자밖에 지원하지 않던 KS X 1001이라는 한국 산업 표준 문자세트를 확장해 만든 것으로, 원래 문자세트의 기존 내용은 보존한 상태로 앞뒤에 부족한 부분을 채워넣었다. (따라서 KS X 1001에 대한 하위 호환성을 가짐) 그럼, cp949는 무엇일까? cp949는 본래 코드 페이지(code page)라는 뜻이라 문자세트라 생각하기 십상이지만, 실제로는 인코딩 방식이다. 즉, MS사가 만든 "확장 완성형 한글 ( 공식명칭 ks_c_5601-1987 ) "이라는 문자세트를 인코딩하는 MS사 만의 방식인 셈이다. cp949 인코딩은 표준 인코딩이 아니라, 인터넷 상의 문자 송수신에 사용되지는 않는다. 하지만, "확장 완성형 한글" 자체가 "완성형 한글"에 대한 하위 호환성을 고려해 고안됐듯, cp949는 euc-kr에 대해 (하위) 호환성을 가진다. 즉 cp949는 euc-kr을 포괄한다. 따라서, 윈도우즈에서 작성되어 cp949로 인코딩 되어있는 한글 문서들(txt, jsp 등등)은 사실, euc-kr 인코딩 방식으로 인터넷 전송이 가능하다. 아니, euc-kr로 전송해야만 한다.(UTF-8 인코딩도 있는데 이것은 엄밀히 말해서 한국어 인코딩은 아니고 전세계의 모든 문자들을 한꺼번에 인코딩하는 것이므로 euc-kr이 한국어 문자세트를 인코딩할 수 있는 유일한 방식임은 변하지 않는 사실이다.) 물론 이를 받아보는 사람도 euc-kr로 디코딩을 해야만 문자가 깨지지 않을 것이다. KS X 1001을 인코딩하는 표준 방식은 euc-kr이며 인터넷 상에서 사용 가능하며, 또한 인터넷상에서 문자를 송수신할때만 사용.(로컬하드에 저장하는데 사용하는 인코딩방식으로는 쓰이지 않는 듯하나, *nix계열의 운영체제에서는 LANG을 euc-kr로 설정 가능하기도 한걸...

한글 인코딩의 이해 : 한글 인코딩의 역사와 유니코드, 그리고 유니코드와 Java를 이용한 한글 처리

출처 : http://helloworld.naver.com/helloworld/76650 NHN Business Platform 쇼핑서비스개발팀 오영은 분명 제대로 보이는 한글 이름의 파일을 내려받았는데 읽을 수 없는 이상한 이름으로 저장된 파일을 받아본 경험이 있을 것입니다. 보통 '인코딩이 깨졌다.'라고 말하는 이런 상황은 왜 발생하는 것일까요? 그 이유는 컴퓨터에서 한글을 표현하는 다양한 방식이 있는데 해당 방식이 서로 맞지 않기 때문입니다. 최초로 컴퓨터가 발명되고 오랜 기간 동안 발전되어 온 지역이 미국이기에 해당 지역에서 사용하는 언어의 문자 집합인 영어 알파벳과 이와 비슷한 문자 체계를 지닌 유럽어 알파벳 처리에 대한 연구가 가장 먼저 시작되었습니다. 이 외의 다른 문자 집합(character set)은 기존에 수립된 인코딩(영어 및 유럽어 문자 집합용)으로 표현하기에는 한계가 있었기 때문에 이들을 처리하기 위한 연구가 추가로 진행되었습니다. 요즘은 어느 전자 기기에서나 한글을 제대로 입력할 수 있고 일부 소형 기기에서는 한글을 더 빠르게 입력할 수도 있어 컴퓨터에서 한글을 처리하는 작업이 너무나 쉽고 당연하게 받아들여지고 있습니다. 하지만 한글을 제대로 표현하기 위한 한글 인코딩 체계가 수립되기까지는 수십 년의 세월이 걸렸습니다. 현재 우리나라에서 주로 사용하고 있는 CP949 또는 EUC-KR(둘은 엄밀히 다릅니다) 인코딩과 유니코드를 제대로 이해하기 위해서는 한글을 표현하기 위한 그간의 역사를 알 필요가 있습니다. 2편 연작으로 기획된 이 기사의 1편에서는 한글 인코딩의 역사를 다루고, 2편에서는 'Java 언어를 기준으로 한글을 처리하는 방법'을 다루도록 하겠습니다. 문자 집합과 인코딩 컴퓨터는 수치 연산을 위해 설계되었다. 컴퓨터 발명 초기에는 문자를 표현해야 하는 요구가 없었다. 영어 단어 'compute'는 단순히 '계산하다'라는 ...