【Python开发】在 PyCharm 上通过 pipenv 配置虚拟环境
1、背景
来都来了,就不用多说为啥了吧 😂
2、安装相关包
2.1、安装 pyenv
以支持同时安装多个版本的 Python
可使用 Homebrew
安装:
$ brew install pyenv
根据自身环境,将下方内容加到对应文件中: .bashrc
/ .zshrc
export PYENV_ROOT=/usr/local/var/pyenv
export PATH="$PYENV_ROOT/bin:$PATH"
export PATH="$PYENV_ROOT/shims:$PATH"
if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi
验证安装是否成功:
$ pyenv
可以看下当前版本:
# 系统版本
$ python -V
Python 3.11.2
# pyenv 所用的版本
$ pyenv version
system (set by /Users/mengxinxin/.pyenv/version)
可以按需下载 Python 版本:
$ pyenv install -v 3.11.2
Downloading Python-3.11.2.tar.xz...
-> https://www.python.org/ftp/python/3.11.2/Python-3.11.2.tar.xz
$ pyenv versions
* system (set by /Users/mengxinxin/.pyenv/version)
3.11.2
切换版本:
$ pyenv global 3.11.2
$ pyenv versions
system
* 3.11.2 (set by /Users/mengxinxin/.pyenv/version)
2.2、安装 pipenv
以支持创建虚拟开发环境
可使用 Homebrew
安装:
$ brew install pipenv
可以配置下,以便将虚拟环境创建在工程目录下:
$ echo 'export PIPENV_VENV_IN_PROJECT=1' >> ~/.bash_profile
$ source ~/.bash_profile
验证安装是否成功:
3、配置虚拟环境
3.1、创建虚拟环境
在要创建虚拟环境的工程 根目录下执行:
# 前往工程的根目录
$ cd ~/Desktop/Python\ Workspace/
# 为该项目初始化了一个 Python 3.9.9的虚拟环境,并在项目录下生成一个项目依赖包文件Pipefile。
# 如果系统中没有该版本的Python,pipenv会调用pyenv来安装对应的Python的版本。
$ pipenv --python 3.9.9
# 为项目安装依赖包到虚拟环境中,使每个项目拥有相互独立的依赖包
# 之后可以通过执行 `$ pipenv uninstall pytest` 来删除
$ pipenv install pytest
# 执行完上面的命令后,检查一下是否安装成功
$ pipenv graph
3.2、在 PyCharm 中配置该虚拟环境
如图打开 PyCharm
的 Preference > Project:<工程名> > Project Interpreter > Add
:
在参考下图步骤,完成添加、配置:
之后,如下图,已经可以正确的加载到刚刚创建的虚拟环境了:
最后,在 PyCharm
的 Terminal
中执行如下命令,就可以在该终端中使用上述虚拟环境了:
# 查看当前的 Python 版本,用的还是全局默认的版本
$ python --version
Python 3.10.3
# 在终端中 进入虚拟环境
$ pipenv shell
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
Launching subshell in virtual environment...
. /Users/mengxinxin/Desktop/Python\ Workspace/.venv/bin/activate
The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
bash-3.2$ . /Users/mengxinxin/Desktop/Python\ Workspace/.venv/bin/activate
# 再次查看当前的 Python 版本,就是虚拟环境指定的 Python 版本了
$ python --version
Python 3.9.9
至此,搞定 ✌️~
附、参考文档
转载自:https://juejin.cn/post/7127489582890745887