Python use Virtualenv create a stand-alone environment.


Virtualenv

Virtualenv is the virtual environment of python.

It can provide a stand-alone operating environment for a python program or script.

Let’s get started.

Install and Using

Install

Install and Using Virtualenv is very simple.

> pip install virtualenv 

Just type in above command in shell, ‘virtualenv’ will be installed immediately.

Tip: For well-known reasons, some python resource packs cannot be downloaded in the country. If you’re experiencing some error stoin, you should to try a scientific way to connect to the Internet.

Activate Command

After the installation is complete. We could just try how to use Virtualenv to create a stand-alone operating environment.

let’s say we’re going to develop a new project that requires a stand-alone Python operating environment, so you can:

# create a directory
> mkdir testProject
> cd testProject

# create a stand-alone Python running environment
# named testVenv:
> virtualenv --no-site-packages testVenv

The Command ‘virtualenv xxx’ is already could create a stand-alone python operating environment. We add the parameters ‘–no-site-packages’ here for keep sure that don’t copy any third-party packages to this environment.

When the shell says ‘Done’, a stand-alone environment is created.

The way to enter the environment varies depending on the operating system.

Linux or MacOS

In Linux or MacOS, you can enter this stand-alone python operating environment simply by using the “Activate” command.

When you enter the environment, the name of the current environment (testVenv) appears at the beginning of the command line for differentiation.

Windows

In Windows, we typically use ‘cmd’ or ‘powershell’ to operate commands. And their operating command are different.

In cmd mode, we still go to the directory and then execute ‘Activate’.

But in powershell mode, we need to execute a policy change first, and then execute ‘activate.ps1’ script to get into a stand-alone environment.

Make sure the current powershell window is under administrator privileges. And here’s the modification command.

# change policy
PS> Set-ExecutionPolicy RemoteSigned
# enter in environment
PS> cd D:\Code\testProject\testVenv\Scripts
PS> .\activate.ps1 
(testVenv) PS>

Some paths in the above sample code have been hidden.

Deactivate

Enter the “deactivate” command directly to shut down the current environment.

Isn’t it very simple? It’s easy to isolate different python environments and avoid them interfering with each other.

In the end

This is my first English technology blog, after which I will try to use English to record all the blogs. I hope it can help me improve my English skill.


文章作者: 游梦
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 游梦 !
   目录