Python - pyenv and venv
Sep 24, 2021
A Little Background !
When I started learning Python and started using it’s various libraries and Frameworks, like most of the beginners I never cared about where I am installng those packages and what problems they are going to create in future.
After few days I got to know about the concept of creating virtual environment for each of our projects, so I started using that, but it was still incomplete. We’ll see how!
For those who don’t know what is virtual environment :
In simple terms you can understand, that we create a environment for our project and then whatever package we install is installed locally, at that project level, not globally.
Why is it even required ?
Suppose we are working on Project A which requires version A of Django , we installed that globally. Now for project B which, suppose, uses Version B of Django things will get worse.
Your Project will not find the correct version it needs to operate and you will get weird errors.
Process I follow for managing Python Projects in my Machine.
Use pyenv to manage different version of Python in your machine.
Use venv to create and use virtual environment.
Let’s me tell you the steps :
- Install pyenv to your machine. [One Time]
- Install as many Python Versions you want using
pyenv install version - Set up one of the version as global using
pyenv global version, by default it is system (don’t use that) [One Time]
Now suppose we want to create a project
- Head over to that directory
- Use
pyenv local versionto declare which python version you want to use for that project.
Previous step will create a .python-version file containing the python version as text.
- Using
python -m venv virtualenvnamewe create a virtual environment. - Using
source virtualenvname/bin/activate, we activate the venv. - Now install any python package you want to install using
python -m pip install pkgname
Hence we setup a project which uses a specific python version of our need.
Also we created a venv so that packages are installed locally, not globally hence no version conflicts in future.
Frequently used commands
pyenv install version: To install a python versionpyenv local version: To use specific python version in your projectpython -m venv venvname: To create Virtual environment.python -m pip install packagename: To install packages
Resources :
-
Tips for installation:
- Complete the prerequisite given.
- Use the Github Checkout Method.
- Make sure to Logout and Login then only changes will take place.