学习地址:https://docs.python-guide.org/dev/virtualenvs/
Make sure you have got python and pip install:
| |
pipenv
Install
pipenv:1$ pip install --user pipenvInstall packages for your project:
1 2 3$ cd myproject $ pipenv install requestsUsing installed packages:
For script file as below (
main.py):1 2 3 4 5import requests response = requests.get('https://httpbin.org/ip') print('Your IP is {0}'.format(response.json()['origin']))Then you can run this script using
pipenv run:1$ pipenv run python main.pyIt’s also possible to spawn a new shell that ensures all commands have access to your installed packages with
1$ pipenv shell
virtualenv
Install virutalenv via
pip:1 2 3 4 5$ pip install virtualenv ... $ virtualenv --version # Test your installationvirtualenv venvwill create a folder in the current directory which will contain the Python executable files, and a copy of thepiplibrary which you can use to install other packages:1 2$ virtualenv <venv> # omitting the name will place the files in the current directory instead.You can also chose your own python interpreter:
1$ virtualenv -p /usr/bin/python2.7 <venv>To begin using the virtual environment, it needs to be activated:
1$ source venv/bin/activateIf you are done working in the virtual environment for the moment, you can deactivate it:
1$ deactivate
virtualenvwrapper
To install (make sure virtualenv is already installed):
1 2 3 4 5$ pip install virtualenvwrapper $ export WORKON_HOME=~/.python_envs $ source /usr/local/bin/virtualenvwrapper.shCreate a virtual environment:
1$ workon <my_project>Alternatively, you can make a project, which creates the virtual environment, and also a project directory inside
$WORKON_HOME, which iscd-ed into when youworkon myproject:1$ mkproject <my_project>Deactivating is still the same:
1$ deactivateTo delete the enviroment:
1$ rmvirtualenv <venv>Other useful commands
lsvirtualenv: List all of the environments.cdvirtualenv: Navigate into the directory of the currently activated virtual environment, so you can browse itssite-packages, for example.cdsitepackages: Like the above, but directly intosite-packagesdirectory.lssitepackages: Shows contents ofsite-packagesdirectory.