大家好,又见面了,我是你们的朋友全栈君。
要搞清楚什么是虚拟环境,首先要清楚Python的环境指的是什么。当我们在执行python
test.py
时,思考如下问题:
PATH
,当我们在命令行中运行程序时,系统会根据PATH
配置的路径列表依次查寻是否有可执行文件python(在windows中,省略了后缀.exe
),当查寻到该文件时,执行该文件; 如果在所有路径列表中都查找不到,就会报报错:'python' 不是内部或外部命令,也不是可运行的程序或批处理文件。
pip
工具或者自己手动安装的包。模块的搜索路径可通过sys.path
查看,主要由可执行文件python所在的位置所决定。Python环境主要包括以下内容:
python.exe
Lib
目录
site-pakages
目录,默认安装第三方库所在的目录Scripts
目录,包含一些执行文件
pip.exe
pyinstaller.exe
(需要自己安装)Python环境主要由运行python解释器的位置所决定。
理解了什么是python环境,思考下为什么有虚拟环境的说法。思考以下问题:
为了解决上面的问题,python使用了虚拟环境这个概念,你可以认为是python环境的多个副本,只是在不同的副本中安装了不同的包。既然叫虚拟环境,总得有点不一样:虚拟环境中一般不包含标准库;不包含python解释器运行时所需的依赖文件;可执行文件全部放于Scripts目录等。
知道了什么是虚拟环境,就应该清楚如何去管理虚拟环境,这就离不开虚拟环境管理工具,下面列出了一些常用的工具,并在稍后的内容中对部分工具的使用作简单的介绍。
C:\Windows
目录)。
py
可以打开默认的 python 提示符; py -2.7
和 py -3
打开对应的 Python 版本,py -0
将列出系统中安装了哪些版本的python
pipenv创建虚拟环境后,会在工程目录生成如下两个文件:
pip install pipenv -i https://pypi.tuna.tsinghua.edu.cn/simple
-i选项指定库的安装源,安装源要满足PEP 503的描述,国内常用的源:
学习使用工具/命令的万能大法 – 查看帮助信息。
pipenv -h
Usage: pipenv [OPTIONS] COMMAND [ARGS]...
Options:
--where Output project home information.
--venv Output virtualenv information.
--py Output Python interpreter information.
--envs Output Environment Variable options.
--rm Remove the virtualenv.
--bare Minimal output.
--man Display manpage.
--support Output diagnostic information for use in
GitHub issues.
--site-packages / --no-site-packages
Enable site-packages for the virtualenv.
[env var: PIPENV_SITE_PACKAGES]
--python TEXT Specify which version of Python virtualenv
should use.
--three / --two Use Python 3/2 when creating virtualenv.
--clear Clears caches (pipenv, pip). [env var:
PIPENV_CLEAR]
-v, --verbose Verbose mode.
--pypi-mirror TEXT Specify a PyPI mirror.
--version Show the version and exit.
-h, --help Show this message and exit.
Usage Examples:
Create a new project using Python 3.7, specifically:
$ pipenv --python 3.7
Remove project virtualenv (inferred from current directory):
$ pipenv --rm
Install all dependencies for a project (including dev):
$ pipenv install --dev
Create a lockfile containing pre-releases:
$ pipenv lock --pre
Show a graph of your installed dependencies:
$ pipenv graph
Check your installed dependencies for security vulnerabilities:
$ pipenv check
Install a local setup.py into your virtual environment/Pipfile:
$ pipenv install -e .
Use a lower-level pip command:
$ pipenv run pip freeze
Commands:
check Checks for PyUp Safety security vulnerabilities and against PEP
508 markers provided in Pipfile.
clean Uninstalls all packages not specified in Pipfile.lock.
graph Displays currently-installed dependency graph information.
install Installs provided packages and adds them to Pipfile, or (if no
packages are given), installs all packages from Pipfile.
lock Generates Pipfile.lock.
open View a given module in your editor.
run Spawns a command installed into the virtualenv.
scripts Lists scripts in current environment config.
shell Spawns a shell within the virtualenv.
sync Installs all packages specified in Pipfile.lock.
uninstall Uninstalls a provided package and removes it from Pipfile.
update Runs lock, then sync.
创建工程目录,并进入工程目录
mkdir test
cd test
创建虚拟环境
pipenv install `--python 3.8`
如果在该工程不录中没有Pipfile文件,则会自动创建Pipfile和Pipfile.lock两个文件;如果该工程目录中有Pipfile,将安装Pipfile列出的相应依赖包,安装完成后生成Pipfile.lock 可以使用如下参数来定义环境:
--python 3.8
将指定该虚拟环境的python使用3.8的最新版本,有以下两种情况 --three
/ --two
使用 Python 3或者2创建虚拟环境--pypi-mirror
指定安装源--site-packages
/ --no-site-packages
是否使用python基础环境中的site-packages路径查看虚拟环境相关信息
#查看工程根目录信息
pipenv --where
#查看当前虚拟环境的信息
pipenv --venv
#查看python解释器的信息
pipenv --py
#查看环境变量选项
pipenv --envs
观察虚拟环境目录的文件 pyvenv.cfg home = d:\programdata\anaconda3 implementation = CPython version_info = 3.8.5.final.0 virtualenv = 20.10.0 include-system-site-packages = false base-prefix = d:\programdata\anaconda3 base-exec-prefix = d:\programdata\anaconda3 base-executable = d:\programdata\anaconda3\python.exe prompt = (test) 这是虚拟环境的配置文件,包含了python环境的相关信息。 .project E:\Projects\test 指定了该虚拟环境对应的工程目录
pipenv shell
注意:
pipenv install
创建虚拟环境,这时pipenv会自动创建相应的虚拟环境。包的安装
pipenv install -h
Usage: pipenv install [OPTIONS] [PACKAGES]...
Installs provided packages and adds them to Pipfile, or (if no packages are
given), installs all packages from Pipfile.
Options:
--system System pip management. [env var:
PIPENV_SYSTEM]
-c, --code TEXT Install packages automatically discovered
from import statements.
--deploy Abort if the Pipfile.lock is out-of-date, or
Python version is wrong.
--site-packages / --no-site-packages
Enable site-packages for the virtualenv.
[env var: PIPENV_SITE_PACKAGES]
--skip-lock Skip locking mechanisms and use the Pipfile
instead during operation. [env var:
PIPENV_SKIP_LOCK]
-e, --editable TEXT An editable Python package URL or path,
often to a VCS repository.
--ignore-pipfile Ignore Pipfile when installing, using the
Pipfile.lock. [env var:
PIPENV_IGNORE_PIPFILE]
--selective-upgrade Update specified packages.
-r, --requirements TEXT Import a requirements.txt file.
--extra-index-url TEXT URLs to the extra PyPI compatible indexes to
query for package look-ups.
-i, --index TEXT Target PyPI-compatible package index url.
--sequential Install dependencies one-at-a-time, instead
of concurrently. [env var:
PIPENV_SEQUENTIAL]
-d, --dev Install both develop and default packages
[env var: PIPENV_DEV]
--keep-outdated Keep out-dated dependencies from being
updated in Pipfile.lock. [env var:
PIPENV_KEEP_OUTDATED]
--pre Allow pre-releases.
--python TEXT Specify which version of Python virtualenv
should use.
--three / --two Use Python 3/2 when creating virtualenv.
--clear Clears caches (pipenv, pip). [env var:
PIPENV_CLEAR]
-v, --verbose Verbose mode.
--pypi-mirror TEXT Specify a PyPI mirror.
-h, --help Show this message and exit.
常用参数示例:
#使用清华源安装numpy包
pipenv install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple
#如果有requirements.txt文件,可以使用下面命令安装requirements.txt列出的包
pipenv install -r path/to/requirements.txt
#安装指定版本的numpy
pipenv install numpy~=1.22.3 #等价于 numpy==1.22.3
#注意,包的版本号可以使用~=、==、>=、 <=、 >、 <、 != 等方式来限制
#在pipenv中,提倡使用 ~= 标识符而不是 == 标识符,因为后者会阻止 pipenv 更新包
思考:在虚拟环境中,使用pip和pipenv都可以安装包,区别在哪里? 使用pipenv安装的包会将相关信息写入Pipfile和Pipfile.lock,而使用pip安装包后,只在虚拟环境的site-packages目录安装了相应包,而不会将信息写入Pipfile和Pipfile.lock
查看虚拟环境中安装的包信息
pipenv graph
包的删除
pipenv uninstall numpy
注意,如果没有激活虚拟环境,即没有运行
pipenv shell
,若想使用pip list
查看虚拟环境中所安装的包时,可以使用pipenv run pip list
exit
pipenv --rm
当退出虚拟环境,删除虚拟环境后,对应的虚拟环境目录会删除掉,但工程目录下的Pipfile.lock和Pipfile两个文件依然存在。
如果已经删除了虚拟环境,可以使用pipenv --python 3.8 install
重新创建虚拟环境以完成下面的示例。
需要共享项目环境时,共享Pipfile文件即可
想要在虚拟环境中执行脚本,比如执行main.py文件,可以使用命令pipenv run python main.py
可以在Pipfile文件中自定义命令,比如在Pipfile末尾添加如下内容,则添加了两个自定义命令print
和list
,分别打印Hello World!
和列出虚拟环境中所装的包:
[scripts]
print = "python -c \"print('Hello World!')\""
list = "pip list"
则可以使用如下方式运行代码
其他
pipenv lock #生成Pipfile.lock.
pipenv sync #安装Pipfile.lock文件中指定的所有包
pipenv update #等价于先lock, 后 sync.
虚拟环境的本质就是修改了sys.path
的值,下面分别查看在虚拟环境和不在虚拟环境中的sys.path
值
在主要的区别在于第三方包的路径时,一个用的是虚拟环境的site-packages,而另一个是使用的python环境中的site-packages。
Python 从3.3 版本开始,自带了一个虚拟环境模块 venv,关于该模块的详细介绍,可参考 PEP-405 和。
查看venv帮助信息:
python -m venv -h
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] ENV_DIR [ENV_DIR ...]
Creates virtual Python environments in one or more target directories.
positional arguments:
ENV_DIR A directory to create the environment in.
optional arguments:
-h, --help show this help message and exit
--system-site-packages
Give the virtual environment access to the system site-packages dir.
--symlinks Try to use symlinks rather than copies, when symlinks are not the default for the platform.
--copies Try to use copies rather than symlinks, even when symlinks are the default for the platform.
--clear Delete the contents of the environment directory if it already exists, before environment creation.
--upgrade Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place.
--without-pip Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default)
--prompt PROMPT Provides an alternative prompt prefix for this environment.
Once an environment has been created, you may wish to activate it, e.g. by sourcing an activate script in its bin directory.
python -m venv venv_demo
这里使用得最多的两个选项为:
--system-site-packages
:是否包含Python系统的site-packages,添加这个选项后,会在sys.path
的末尾添加上系统的site-packages相关目录。不添加这个选项时,将不会包含系统的site-packages--without-pip
:虚拟环境中是否包含pip.exe在虚拟环境的Scripts目录中有两个脚本文本activate.bat
和deactivate.bat
,分别用于激活虚拟环境和退出虚拟环境。
注意:
当我们激活虚拟环境后,系统的PATH路径的最前面添加了虚拟环境的Scripts目录,该目录下包含了pip.exe和python.exe。可以得到如下结论:
注意,这里使用的PowerShell,所以查看path环境变量时使用的
$env:path
,如果是CMD,查看环境变量可以使用echo %PATH%
使用pip工具进行虚拟环境中包的管理,有两种方式
pip命令的基本使用将在文末介绍。
conda支持Python、R、Java、JavaScript、C等多种开发语言的包、依赖和环境管理工具,能运行在Windows、MacOS、Linux多个平台,可以在本地轻松创建、保存、切换环境。当安装anaconda时,会自动安装conda工具。
conda与pipenv,venv等虚拟环境管理工具的最大的不同在于:conda虚拟环境是独立于操作系统解释器环境的,即无论操作系统解释器什么版本(哪怕2.7),我也可以指定虚拟环境python版本为3.6,而venv是依赖主环境的。
conda create --name py3.6 python=3.6
创建好虚拟环境后,你会发现虚拟环境py3.6的内容与一个实体python环境是一样的。所以,conda的环境管理更像是实体环境的一个拷贝,而不像是一个虚拟环境
conda activate py3.6
conda deactivate
#安装numpy模块
conda install numpy
#查看已安装的模块
conda list
#搜索模块信息
conda search numpy
#删除模块
conda remove numpy
#更新模块
conda update numpy
#更新全部模块:
conda update --all
#更新conda
conda update conda
#更新python
conda update python
使用conda安装包往往很慢,需要设置conda的国内源,具体做法如下: 生成.condarc配置文件 conda config --set show_channel_urls yes 修改.condarc channels: - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2 - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/pro - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2 - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/bioconda - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/menpo - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/simpleitk - defaults show_channel_urls: true ssl_verify: true 也可以使用如下命令添加源 conda config --add channels 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/' 查看设置的源 conda --show channels 也可以使用
conda info
查看基本信息
conda remove --name py3.6 --all
conda env list
查看帮助:
pip -h
Usage:
pip <command> [options]
Commands:
install Install packages.
download Download packages.
uninstall Uninstall packages.
freeze Output installed packages in requirements format.
list List installed packages.
show Show information about installed packages.
check Verify installed packages have compatible dependencies.
config Manage local and global configuration.
search Search PyPI for packages.
cache Inspect and manage pip's wheel cache.
wheel Build wheels from your requirements.
hash Compute hashes of package archives.
completion A helper command used for command completion.
debug Show information useful for debugging.
help Show help for commands.
General Options:
-h, --help Show help.
--isolated Run pip in an isolated mode, ignoring environment variables and user configuration.
-v, --verbose Give more output. Option is additive, and can be used up to 3 times.
-V, --version Show version and exit.
-q, --quiet Give less output. Option is additive, and can be used up to 3 times (corresponding to
WARNING, ERROR, and CRITICAL logging levels).
--log <path> Path to a verbose appending log.
--no-input Disable prompting for input.
--proxy <proxy> Specify a proxy in the form [user:passwd@]proxy.server:port.
--retries <retries> Maximum number of retries each connection should attempt (default 5 times).
--timeout <sec> Set the socket timeout (default 15 seconds).
--exists-action <action> Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup,
(a)bort.
--trusted-host <hostname> Mark this host or host:port pair as trusted, even though it does not have valid or any
HTTPS.
--cert <path> Path to alternate CA bundle.
--client-cert <path> Path to SSL client certificate, a single file containing the private key and the
certificate in PEM format.
--cache-dir <dir> Store the cache data in <dir>.
--no-cache-dir Disable the cache.
--disable-pip-version-check
Don't periodically check PyPI to determine whether a new version of pip is available for
download. Implied with --no-index.
--no-color Suppress colored output
--no-python-version-warning
Silence deprecation warnings for upcoming unsupported Pythons.
--use-feature <feature> Enable new functionality, that may be backward incompatible.
--use-deprecated <feature> Enable deprecated functionality, that will be removed in the future.
1)安装requirements.txt文件列出的包
pip install -r requriements.txt
2)安装指定包
pip install numpy
3)安装whl文件
pip install wheel
pip install xxxx.whl
常用参数主要包括:
-i <url>
或者 --index-url <url>
:指定安装源,通常设为国内源会更快pip install --upgrade 包名称
如果要指定升级到某个版本,可以使用
pip install --upgrade 包名称==版本号
注意:不要使用pip install --upgrade pip
更新pip自身,否则会在更新pip的时候删除掉pip,然后出现No module named ‘pip’的情况 ,可运行如下命令安装pip: python -m ensurepip 如果要更新pip自身,可以使用如下命令: python -m pip install --upgrade pip
删除指定的包
pip uninstall 包名
删除requriements.txt文件中列出的包
pip uninstall -r requriements.txt
列出安装的所有包:
pip list
查看某一个包的具体信息
pip show 包名
pip freeze > requirements.txt
导出pip所在环境中所安装的所有包,将其输出到requirements.txt文件中
在创建pycharm工程时,记得指定python解释器为虚拟环境中Scripts目录下的python.exe即可
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/175522.html原文链接:https://javaforall.cn