Skip to content

[Python] How to Build a Python Virtual Environment in a Folder

All the time unless I just want to write a simple test, or a single script, statistical program… I have always created a python virtual environment for the project I am developing.

When I was training the model in the past, it was caused by the version conflict of Numpy. At that time, I upgraded Numpy and model A would no longer be trained; I downgraded Numpy and model B died…

The final solution of this problem is to place it in a different virtual environment. In this way, both parties can install packages that meet their own needs, which is gratifying.


Use venv to build a virtual environment

In Ubuntu/Debian or other Linux distributions, you can use the following command to install the package:

sudo apt-get install python3-venv


After installation, you can use following command to build the python virtual environment, the folder does not need to be created in advance. (Suppose the virtual environment I want to build is called “Blog”)

python3.6 -m venv Blog
cd Blog/
ls

Output:

bin include lib lib64 share pyvenv.cfg


Then, to activate this virtual environment, we need to use the following command:

source bin/activate

In the Windows environment, the “activate.bat” file is also to be found.


After the virtual environment is started, the word “(Blog)” should be marked at the top of the terminal. Of course, the name of your virtual environment will be different from mine, it will be your own name.


Then came to the important part. Let’s take a look at the python packages in this environment.

pip3 list

Output:

pip (9.0.1)
pkg-resources (0.0.0)
setuptools (39.0.1)

We can see that the environment is very pure! There is no extra package.


Then we use pip3 to install the new package, and we will find that the package will only be installed in this virtual environment.

pip3 install numpy
pip3 list

Output:

numpy (1.18.3)
pip (9.0.1)
pkg-resources (0.0.0)
setuptools (39.0.1)

Deactivate the virtual environment

It is equally simple to close the virtual environment, use the following command:

deactivate

Seeing (Blog) on the leftmost side of the terminal command line disappears, it means success.


References

Tags:

Leave a Reply