A real simple and quick VirtualEnv guide
3 min read
A real quick and simple note on creating Virtual Environments in Python.
You'll need Python3 installed, with Pip, and VirtualEnv installed.
virtualenv with pip
First, install virtualenv using pip
pip3 install virtualenv
Then create a virtualenv at the path ~/venv/myvenv
mac or windows
#method 1 python3 -m venv ~/venv/myvenv #method 2 virtualenv ~/venv/myvenv -p python3
Don't forget to activate
Of course, you'll validate that you're activated by the parenthesized env name
(myvenv) $ which python /home/dir/venv/myvenv/bin/python
You can "shabang" your python scripts directly to this instance of python that includes your modules, that way your scripts always run with the correct version. Keep in mind the portability of your script though, as this path may change on other devices.
Exit your venv with the command:
Using pipenv can simplify the virtualenv process tremendously
You can install with your local package manager (apt, dnf, pkg, pip, brew)
pip install pipenv
brew install pipenv
Navigate to your development directory and run this to create a Python3 environment.
The Pipfile manages what's needed for the project. Now use pipenv to install packages
pipenv install bs4
Installing bs4... Adding bs4 to Pipfile's [packages]... ✔ Installation Succeeded Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Building requirements... Resolving dependencies... ✔ Success! Updated Pipfile.lock (8cf921)! Installing dependencies from Pipfile.lock (8cf921)... 🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/0 — 00:00:00 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run.
You can run your script with any of these commands
###straight python from the project dir .venv/bin/python bs4test.py ###from the pipenv shell pipenv shell python bs4test.py ###with pipenv run pipenv run python bs4test.py
I'm still learning the tricks of pipenv, so I'll have another writeup on the value of pipenv in the future.