前提
- 已经有一个python环境
安装
- pip install virtualenv
创建环境
- 进入一个目录(任意指定)
- 执行命令 virtualenv TestEnv(虚拟环境名字)
- 将会在当前的目录中创建一个文件夹,包含了Python可执行文件,以及
pip
库的一份拷贝,这样就能安装其他包了。- 虚拟环境的名字可以是任意的;
- 若省略名字将会把文件均放在当前目录。
默认情况下创建的虚拟环境会依赖于系统中的site-packages,即系统中已经安装好的库在虚拟环境中仍然可以使用。如果想去除依赖,那么可以virtualenv -
-no
-site
-packages
2.你也可以选择使用一个Python解释器:virtualenv -p /usr/bin/python2.7 TestEnv # -p参数指定Python解释器程序路径 这将会使用 /usr/bin/python2.7
。
windows执行完 virtualenv TestEnv后会有四个目录:Includ、Lib、Scripts、tcl
linux执行完virtualenv TestEnv后会有三个目录:bin、 include、lib
激活环境
- windows:进入TestEnv/Scripts目录 执行activate命令即可激活
- linux:进入TestEnv/bin目录,执行source activate命令即可激活
启动后,shell的提示符就会发生改变,表示进入了虚拟环境。
执行文件
- 在python虚拟环境激活的条件下,进入到python工程的主目录,直接执行python xx.py命令即可用python虚拟环境运行python文件
离开虚拟环境
- 执行命令deactivate离开虚拟环境
pycharm中的虚拟环境
- 在pycharm中选择File->Setting->Project: untitled->Project Interpreter
- 在Project Interpreter下拉框中选择创建好的虚拟环境路径(点击后边的配置按钮选择Add Local,选择虚拟环境中的Scripts文件夹中的python.exe即可)
linux下安装多版本python
当一个电脑中的python版本过多时,使用pip会报错 ,例如pip3.6 -> failed to create process 或 fatal error in launcher:unable to create using process
可改成python3.6 -m pip 来代替pip3.6
或 执行下列命令
python3.6 -m pip install --upgrade pip
若其他命令也出现问题 也使用 【python3.6 -m +命令】 来代替 【命令】