Python3 virtual environment construction
1. Perface
Why do we need virtual environment
Simply put, an individual virtual environment can be used by an individual python project so that every project won’t affect each other and also won’t affect the python system environment.
Why do we use ‘virtualenv’
In short, it’s the python official recommendation.
2. Install virtualenv
PS: My laptop is MacBook, so the following procedure is based on the macbook terminal.
Before installing, you should make sure you’ve already installed pip, and then use pip to install env.
pip3 install virtualenv
Check if the installation is successful
virtualenv –version
Create the big virtual environment
Firstly, you should ‘cd’ to the directory where you wanna create VE(virtual environment)
virtualenv envname #Here you should give your virtual environment name
The environment will also install Python setuptools, pip, wheel automatically
Activate your environment
Source bigenvname/bin/activate
Extra procedure
For me, I often use terminal to start the editor, so when you activate the environment, Use ‘cd’ to the directory where you wanna store your code file. And then start jupyter notebook.
jupyter notebook
So now you can code in the envname virtual environment.
3. Install virtualenvwrapper
*Note: Sometimes, we may create more than one VE, and we’d like to swap between the different VE. Hence, we need the command ‘workon’ which is belong to the package virtualenvwrapper.
Install VEW.
pip3 install virtualenvwrapper
Configure VEW.
export WORKON_HOME=’your sub-VE address’
source /usr/local/bin/virtualenvwrapper.sh // execute the command package
But what if your address is not the above default address, how could you find it? I faced the same problem before. We can try to uninstall the package ‘virtualenvwrapper’ and it will prompt us all the files address we would delete.
![截屏2021-02-20 13.24.51](/Users/arieskoo/Library/Application Support/typora-user-images/截屏2021-02-20 13.24.51.png)
After configuring all the environment parameters, we s=also need to execute source command to make it work.
source ~/.bash_profile
4. Use VEW to create sub-environment
create sub-env
makvirtualenv env01(envname)
The default address is under the previous export WORKON_HOME=’your sub-VE address’.
Query the list of VE
lsvirtualenv -b
query the python pakcages
lssitepackages
exchange the sub-VE
workon envname
Remove sub-VE
rmvirtualenv envname
Install python packages in the sub-VE
pip install packagename
exit the sub-VE
deactivate
How to start VE every time start the PC
Since you totally exit the VE, you need to reactivate the big VE every time you wanna reenter it.
cd big VE address
source bigenvname/bin/activate
workon sub-VEname