DEV Community

postrecord
postrecord

Posted on

Why use virtual environments?

A virtual environment (venv) in Python is isolated from the rest of the system. This is necessary, because packages can conflict and sometimes packages are malicious.

First install the program virtualenv

sudo apt install virtualenv
Enter fullscreen mode Exit fullscreen mode

Then you can create a new project (hello):

virtualenv -p /usr/bin/python3 hello  
cd hello
source bin/activate
Enter fullscreen mode Exit fullscreen mode

On my machine:

C:\home\frank\example> ls
hello
C:\home\frank\example> cd hello 
C:\home\frank\example\hello> ls
bin  lib  pyvenv.cfg
C:\home\frank\example\hello> source bin/activate        
(hello) C:\home\frank\example\hello> ls             
bin  lib  pyvenv.cfg
(hello) C:\home\frank\example\hello> 
Enter fullscreen mode Exit fullscreen mode

Then you can add any Python files you want. Install modules with pip, they will exist only in this virtual environment.

This prevents package conflicts. You can even set a custom Python version. Added bonus: Even if the module contains malware, it won't affect your operating system.

To exit your virtual environment, just type exit.

(hello) C:\home\frank\example\hello> exit
Enter fullscreen mode Exit fullscreen mode

Automatic venv

If you use an IDE, then the IDE will create the virtual environments for you. For beginners, that's the recommended way.

In PyCharm for example, you don't have to do anything except create a new project or open an existing project. It takes care of everything for you.

pycharm virtual environment

I'm not 100% sure what other Python IDE's do in terms of the virtual environment, but I'm quite sure they set it up too.

An IDE will also help you with debugging, but you can do that from the terminal too.

Top comments (0)