# Windows安装pydot/pydot-ng和Graphviz并解决安装后仍然报错的问题

> 作者：zning（https://ning.ae） · 发布：2019/06/17 21:30 下午 (UTC+8) · 原文：https://zning.me/15607782136613.html

近期因为需要安装Graphviz和pydot/pydot-ng，但是发现安装后在conda的Python里仍然报错。经过多次查找终于找到了合适的解决方法，现记录如下。

> 注意：本文首次撰写于2019-06-17，最近修改时间为2019-06-17，请注意相关程序的可用性与安全性。

## 安装顺序

**先安装graphviz，再安装pydot-ng**

## 安装Graphviz

到官网下载graphviz的安装包，[这里我提供个链接](https://graphviz.gitlab.io/_pages/Download/windows/graphviz-2.38.msi), 并记住安装路径，比如在我的电脑上它的安装路径是`C:\Program Files (x86)\Graphviz2.38`。

然后将该目录下的bin文件夹添加到系统的环境变量中，即把`C:\Program Files (x86)\Graphviz2.38\bin`添加进环境变量中，最后在cmd输入`dot -version`并按回车，若显示出graphviz的相关版本信息，则安装配置成功。 

按照这样安装了之后，再安装pydot/pydoc-ng。

## 安装pydot/pydoc-ng

```shell
pip install pydot-ng
```

请注意这里不要安装pydot。

此时，运行可视化模型的脚本：
```python
from keras.utils.vis_utils import plot_model
plot_model(model, to_file=“model.png”,show_shapes=True)
```
会出现需安装pydot的错误提示，如果此时安装pydot包——当然你不需要再尝试安装了——后续运行上述脚本，仍然会报错：
```
pydot failed to call GraphViz.Please install GraphViz (https://www.graphviz.org/) and ensure that its executables are in the $PATH.
```
由于我已经将GraphViz的安装路径添加到path中，这个报错应是pydot与keras的版本匹配问题，这需要修改keras.utils中vis_utils.py脚本中的代码。我的keras.utils地址：`\Anaconda\Lib\site-packages\keras\utils`，仅供参考。

```python
# 原始代码
try:
    import pydot
except ImportError:
    pydot = None
```

修改为如下情况

```python
# 修改后
try:
    import pydot_ng as pydot
except ImportError:
    try:
        import pydotplus as pydot
    except ImportError:
        try:
            import pydot
        except ImportError:
            pydot = None
```

## 参考文献

1. https://blog.csdn.net/WuchangI/article/details/79589542
2. https://blog.csdn.net/xu_haim/article/details/84981284
