4: Virtual Environments(Command line Python scripting )

来源:互联网 发布:瑞士 知乎 编辑:程序博客网 时间:2024/06/05 15:18

In the previous screen, we used the default version of pip, which installed requests for thepython executable, which is Python version 2.

What if we had instead wanted to installrequests for Python 3? This type of version switching can get confusing, and different projects can require different packages and Python versions. A nice way to avoid issues with different package versions are virtual environments. By default, the system has onepython executable, and you have to install all packages and libraries globally. This means that every single project on your machine has to use the same version of Python, and the same versions of every package.

By default, you can't use different versions of Python without some hacks. One such hack is renaming python to python3 so we can have access to both Python 2 and Python 3.

A better solution for this is for each project we write to have its own version of Python, along with its own packages. This way, we don't need to worry that upgrading the version of a package will affect other projects on the system and cause them to stop working.

Virtual environments, or virtualenvs, let us do this. You can create a new virtualenv with thevirtualenv command. In order to access this, you normally have to install the virtualenv package, but we've already installed it to simplify the process.

Typing virtualenv main will create a virtualenv named main. It will create a folder in the current directory called main that will hold all the packages you install into the virtual environment.

Instructions

Type virtualenv python2 in the /home/dq directory to create a new virtual environmented named python2.

  • Note how it makes a folder called python2.

/home/dq$ virtualenv python2                                                    
New python executable in /home/dq/python2/bin/python                            
Installing setuptools, pip, wheel...                                            
                                          

0 0