
1.7 在PyCharm 中使用Anaconda 的环境
1.7.1 新建和配置项目
打开Python 的集成开发环境PyCharm,选择 “File”→“New Project” 菜单命令,新建项目(图1-34)。

图1-34 新建项目
单击图1-35 中 “Location” 右侧的浏览按钮,在弹出的对话框中单击新建文件夹按钮,新建名为demo 的文件夹,然后单击 “OK” 按钮,即完成项目保存路径的选择(图1-36)。

图1-35 新建项目选项

图1-36 选择项目保存路径
接下来回到图 1-35 所示的对话框,单击 “Project Interpreter:New Virtualenv environment” 前面的三角形按钮,展开选项,如图1-37 所示。

图1-37 新建项目详细选项
其中,“Location” 表示环境存放在demo 项目的venv 文件夹下。
“Base interpreter” 为基础解释器,这里选择Anaconda 安装目录中envs 文件夹下已有环境TensorFlow 中的python.exe。
注意:一定要勾选下面两个选项。
● “Inherit global site-packages”(继承全局站点包,如果不选此项,则TensorFlow和OpenCV 需要单独安装)。
● “Make available to all projects”(当前新建环境可用于所有项目,下次新建项目时,可以在 “Existing interpreter” 中选择该环境)。
单击 “Create” 按钮创建项目,在弹出的对话框中选择 “New Window”,即在新窗口中打开项目(图1-38)。打开新建项目后,PyCharm 界面左侧会显示该项目的目录结构(图1-39)。

图1-38 在新窗口中打开项目

图1-39 显示项目的目录结构
1.7.2 再次查看项目配置
在PyCharm 菜单栏中选择 “File”→“Settings” 命令,打开设置对话框(图1-40)。单击左侧 “Project: demo” 下面的 “Project Interpreter”,右侧将显示环境中各个包的当前版本和最新版本。

图1-40 设置对话框
1.7.3 运行案例代码
在PyCharm 界面中右击项目名称,在弹出的快捷菜单中选择“New”→“Python File” 命令,新建Python 文件,并将文件命名为 “demo”(图1-41)。在Python 文件中输入如下代码。

在代码编辑区右击并选择运行命令,之后可以在下方控制台中看到代码运行结果(图1-42)。
注意,如果Python 文件中第一行代码处有红色波浪线出现,说明没有可用的TensorFlow 包,这表示之前的安装和配置有问题,应按照安装步骤重新安装。

图1-41 新建Python 文件

图1-42 代码运行结果