一、问题的引出
由于笔者经常在不同电脑上进行同一项目的编程优化工作,并通过OneDrive进行同步,这就导致在不同电脑上运行的时候需要重新配置python环境和安装程序依赖包。因此笔者决定通过在项目文件夹下面配置虚拟运行环境(virtual environment),解决不同电脑上的运行项目程序需要频繁修改python解释器位置和手动更新程序依赖包的问题。
二、Python解释器(Python interpreter)
Python程序运行依赖于Python解释器,Python解释器是通过安装python可执行文件(Python executable)来生成的,而安装一个python可执行文件可以生成多个Python解释器(You can create several Python interpreters based on the same Python executable. This is helpful when you need to create different virtual environments for developing different types of applications.)。Python解释器分为两种,既可以是通过标准python可执行文件生成的系统解释器,也可以是通过 Virtualenv, Pipenv, and Conda来生成的虚拟解释器。由于Pycharm整合了Virtualenv,因此不必额外安装,直接可以使用。
三、配置虚拟环境过程
正如前面所述,我们的项目因为拥有许多依赖包,因此在配置虚拟环境前需要先将项目中的依赖包导出。导出过程为先进入到Pycharm的命令行终端(既可以点击pycharm左下角的terminal标签进入,也可以通过菜单栏的View - Tool Windows - Terminal打开),然后在确保终端路径是当前项目主文件夹的情况下,输入 pip freeze > requirements.txt,即可在项目主文件夹下生成requirements.txt 文件,里面包括所有依赖包和版本号。
注意:采用pip freeze > requirements.txt 生成的依赖包不只是本项目的依赖包,还带有基本python环境的site-packages,因此更好的方法是安装并使用pipreqs,抽离出本项目的依赖包:
# 安装 pip3 install pipreqs
# 使用步骤 1.在项目根目录下执行命令 pipreqs ./ # 报错就执行下面这条(UnicodeDecodeError: 'gbk' codec can't decode byte 0xa8 in position 2234: illegal multibyte sequence) pipreqs ./ --encoding=utf-8 2.可以看到生成了requirements.txt文件 3.执行下面代码就会把项目用到的所有组件装上 pip3 install -r requirements.txt
此时即可建立虚拟环境了,通过菜单栏打开File - Setting - Project: XXX - Project Interpreter, 点击齿轮 - add, 进入 add Python Interpreter界面
继而
1.点选Virtualenv Environment - 选择New environment,在location下选择虚拟环境的安装位置(注意文件夹一定要是空的! Note that the directory where the new virtual environment should be located, must be empty!)
2.在base interpreter里选择任意一个安装在本机上的Python.
3.点选Inherit global site-packages,以便可以使用步骤2中Python第三方库,否则将与外界完全隔离(Select the Inherit global site-packages checkbox if you want to inherit your global site-packages directory. This checkbox corresponds to the --system-site-packages
option of the virtualenv tool.)
4.点选Make available to all projects使此虚拟环境可以提供给其他项目使用。
5. 打开新生成的虚拟环境,再次进入上述的Pycharm命令行终端,运行pip install -r requirements.txt,以安装依赖包。(笔者打开此虚拟环境的时候,已经自动安装完毕了,如果没有自动安装,则可运行前述代码pip install -r requirements.txt)
注意,有时候Pycharm仿佛反应不过来,会提示你相关包在别的地方已经安装了“Requirement already satisfied: setuptools in d:\programdata\anaconda3\lib\site-packages (from kiwisolver==1.0.1->-r requirements.txt (line 15)) (41.4.0)”, 这时候只需要执行以下命令指定安装路径如: pip install --target="D:\OneDrive - BHB\projects\reward-based system\sumo_ITS\venv\Lib\site-packages" -r requirements.txt
此外,我更新完以后还有几个小错误,如:“ImportError: No module named '_cvxcore';ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' 等”,只需要更新下numpy就解决了。
References
Configure a Python interpreter Configure a Python interpreter | PyCharm