学习地址:https://docs.python-guide.org/dev/virtualenvs/
Make sure you have got python
and pip
install:
|
|
pipenv
Install
pipenv
:1
$ pip install --user pipenv
Install packages for your project:
1 2 3
$ cd myproject $ pipenv install requests
Using installed packages:
For script file as below (
main.py
):1 2 3 4 5
import 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.py
It’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 installation
virtualenv venv
will create a folder in the current directory which will contain the Python executable files, and a copy of thepip
library 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/activate
If 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.sh
Create 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
$ deactivate
To 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-packages
directory.lssitepackages
: Shows contents ofsite-packages
directory.