Python虚拟环境使用

之前安装完成Python虚拟环境之后,过了一段时间就发现已经完全记不起怎么操作了,发现之前《Python虚拟环境配置》文章不能很好指导怎么操作,接下来补充说明以方便后续回顾使用。
之前文章有说明在virtualenvwrapper安装过程中需要配置.bashrc文件,如果登出了虚拟机上客户端操作系统,再一次登录之后,需要运行命令启动.bashrc文件,因为.bashrc是在登录时执行,因此运行下面的命令后可以使用virtualenvwrapper命令。

$ source ~/.bashrc

之后可以输入命令mkvirtualenv --help确认是否可用。

$ mkvirtualenv --help
Usage: mkvirtualenv [-a project_path] [-i package] [-r requirements_file] [virtualenv options] env_name

 -a project_path

    Provide a full path to a project directory to associate with
    the new environment.

 -i package

    Install a package after the environment is created.
    This option may be repeated.

 -r requirements_file

    Provide a pip requirements file to install a base set of packages
    into the new environment.

virtualenv help:

Usage: virtualenv [OPTIONS] DEST_DIR

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -v, --verbose         Increase verbosity.
  -q, --quiet           Decrease verbosity.
  -p PYTHON_EXE, --python=PYTHON_EXE

使用virtualenvwrapper创建虚拟机的运行环境,创建后就处于激活状态。

$ mkvirtualenv py3env
MacBook~$  mkvirtualenv --python=/usr/local/bin/python3 py3env
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/MacBook/.virtualenvs/py3env/bin/python3.6
Also creating executable in /Users/MacBook/.virtualenvs/py3env/bin/python
Installing setuptools, pip, wheel...done.
virtualenvwrapper.user_scripts creating /Users/MacBook/.virtualenvs/py3env/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/MacBook/.virtualenvs/py3env/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/MacBook/.virtualenvs/py3env/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/MacBook/.virtualenvs/py3env/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/MacBook/.virtualenvs/py3env/bin/get_env_details
(py3env)  MacBook~$ 

用下面的命令对这一目录进行确认,看一下是否有py3env目录生成

MacBook~$  ls -la $HOME/.virtualenvs
drwxr-xr-x   7 MacBook  staff   216  9 15 07:36 py3env

可以使用workon命令查看和进入已创建虚拟环境,deactivate退出。

MacBook~$ workon
myenv
py3env
MacBook~$ workon myenv
(myenv)  MacBook~$
(myenv)  MacBook~$ deactivate
MacBook~$

删除虚拟运行环境

MacBook~$  rmvirtualenv py3env

推荐阅读更多精彩内容