在使用virtualenv
前ubuntu默認的解釋器是python2.7,並且/usr/lib/python3
裏面已經安裝好了ipython3
和requests
python
$ python Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
$ ipython3 Python 3.5.2 (default, Nov 17 2016, 17:05:23) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import requests In [2]:
因爲一些兼容性問題,電腦上默認的python版本只能只能使用python2.7,因此建立命令要另外使用-p
指定解釋器linux
$ mkdir my_project_folder; cd my_project_folder # 建立虛擬環境 $ virtualenv -p /usr/bin/python3 venv Running virtualenv with interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /home/ormsf/my_project_folder/venv/bin/python3 Also creating executable in /home/ormsf/my_project_folder/venv/bin/python Installing setuptools, pkg_resources, pip, wheel...done.
激活虛擬環境ubuntu
$ source venv/bin/activate
如今能夠看到提示符前面多了一個venv
,表明虛擬環境建立成功bash
(venv) ~/my_project_folder $ ipython3
實踐一下,虛擬環境和實際的環境隔離的python2.7
# 沒法使用ipython3 (venv) ~/my_project_folder $ ipython3 Traceback (most recent call last): File "/usr/bin/ipython3", line 4, in <module> from IPython import start_ipython ImportError: No module named 'IPython' # 默認的解釋器已經變成了python3 (venv) ~/my_project_folder $ python Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. # 沒法使用requests >>> import requests Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named 'requests'
注意不須要使用pip3ui
(venv) ~/my_project_folder $ pip install requests Collecting requests Downloading requests-2.13.0-py2.py3-none-any.whl (584kB) 100% |████████████████████████████████| 593kB 1.3MB/s Installing collected packages: requests Successfully installed requests-2.13.0
如今request已經可以正確使用了code
(venv) ~/my_project_folder $ python Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>>
(venv) ~/my_project_folder $ pip install ipython
如今ipython也已經可以正確使用了orm
(venv) ~/my_project_folder $ ipython Python 3.5.2 (default, Nov 17 2016, 17:05:23) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]:
退出ip
(venv) ~/my_project_folder $ deactivate
原理很簡單,就是把系統Python複製一份到virtualenv的環境,用命令source venv/bin/activate
進入一個virtualenv環境時,virtualenv會修改相關環境變量,讓命令python和pip均指向當前的virtualenv環境。requests