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
Then you can create a new project (hello):
virtualenv -p /usr/bin/python3 hello
cd hello
source bin/activate
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>
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
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.
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)