A real quick and simple note on creating Virtual Environments in Python.
Setup
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
unix
source ~/venv/myvenv/bin/activate
windows
~/venv/myvenv/Scripts/activate.ps1
Of course, you'll validate that you're activated by the parenthesized env name
(myvenv) $ which python
/home/dir/venv/myvenv/bin/python
unix
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.
#!/home/dir/venv/myvenv/bin/python
Exit your venv with the command:
deactivate
Using pipenv
Using pipenv can simplify the virtualenv process tremendously
You can install with your local package manager (apt, dnf, pkg, pip, brew)
windows
pip install pipenv
mac
brew install pipenv
Navigate to your development directory and run this to create a Python3 environment.
pipenv --three
The Pipfile manages what's needed for the project. Now use pipenv to install packages
pipenv install bs4
output
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.
- AJ