
上QQ阅读APP看书,第一时间看更新
How to do it...
Install and test the virtual environment using the following steps:
- Open a command-line shell and type in the following command:
pip install virtualenv
Alternatively, you can type in the following command:
sudo pip install virtualenv
- Once installed, type virtualenv in the command window, and you should be greeted with the information shown in the following screenshot:

- Create a temporary directory and change location to this directory using the following commands:
mkdir temp cd temp
- From within the directory, create the first virtual environment named venv:
virtualenv venv
- You should see text similar to the following:
New python executable in venv/bin/python Installing setuptools, pip...done.
- The new local Python distribution is now available. To use it, we need to activate venv using the following command:
source ./venv/bin/activate
- The activated script is not executable and must be activated using the source command. Also, note that your shell's command prompt has probably changed and is prefixed with venv to indicate that you are now working in your new
virtual environment. - To check this fact, use which to see the location of Python, as follows:
which python
You should see the following output:
/path/to/your/temp/venv/bin/python
So, when you type python once your virtual environment is activated, you will run the local Python.
- Next, install something by typing the following:
pip install flask
Flask is a micro-web framework written in Python; the preceding command will install a number of packages that Flask uses.
- Finally, we demonstrate the versioning power that virtual environment and pip offer, as follows:
pip freeze > requirements.txt cat requirements.txt
This should produce the following output:
Flask==0.10.1 Jinja2==2.7.2 MarkupSafe==0.19 Werkzeug==0.9.4 itsdangerous==0.23 wsgiref==0.1.2
- Note that not only the name of each package is captured, but also the exact version number. The beauty of this requirements.txt file is that, if we have a new virtual environment, we can simply issue the following command to install each of the specified versions of the listed Python packages:
pip install -r requirements.txt
- To deactivate your virtual environment, simply type the following at the shell prompt:
deactivate