graphviz.backend.execute.ExecutableNotFound: failed to execute WindowsPath(‘dot‘), make sure the Gra

博客讲述了在Python中使用Graphviz库实现求解两点间所有路径的算法,并遇到图形化展示时的ExecutableNotFound错误。解决方案包括卸载并重新安装Graphviz库,从官网下载安装包,确保将其添加到环境变量中。通过示例代码展示了如何读取图数据,找到路径并生成PDF报告。最终成功解决问题,显示了所有找到的路径和图形化结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

场景:

报错:

解决:

目录结构:

输入数据:

主函数: 

输出效果:


场景:

我在使用graphviz这个第三方库,python实现求两点间所有路径的算法 并使用 graphviz 图形化展示路径。

报错:

graphviz.backend.execute.ExecutableNotFound: failed to execute WindowsPath('dot'), make sure the Graphviz executables are on your systems' PATH

解决:

大家习惯pip install graphviz去安装,但是graphviz是个软件,不能单独用Pip安装。

(1)先将自己安装好的卸载

pip uninstall graphviz

(2)首先要重新安装这个第三方库,

pip install graphviz

(3)然后下载graphviz的安装包 ,网址: 

https://graphviz.org/download/

进入下面页面。此处我选择这个版本进行下载, 

(4)下载之后,点击下载成功的.exe文件(本文简称graphziv.exe)进行安装,一路默认即可,安装的时候记住安装路径(最好放到anaconda文件夹下,即**\Anaconda\Graphziv后续配置环境变量的时候要使用) ,

在安装过程中,一定要注意:将之加入到环境变量中去

(5)如果没有加入请参考此步骤进行添加环境变量,

1.此电脑右键----->属性----->高级系统设置----->环境变量----->xxx的用户变量u----->path----->新建

粘贴文件的安装路径+\bin :例如D:\python\graphviz\bin

2. 此电脑右键----->属性----->高级系统设置----->环境变量----->系统环境变量(s)----->path----->新建
粘贴文件的安装路径+\bin\dot.exe :例如D:\python\graphviz\bin\dot.exe

 (6)运行我的py代码,

目录结构:

 其中,

输入数据:

graph.txt:

代码应能读取规定格式的TXT文档作为输入,格式如下:

  • 第一行:图的节点数N,边数V

  • 后续V行: 图中每一条边的起点、终点

  • 最后一行:待求解目标的起点、终点

16 20
1 2
1 5
2 3
2 4
3 4
3 5
4 5
5 7
5 14
5 6
6 9
7 4
9 4
10 6
11 5
12 7
13 8
13 6
15 13
16 10
2 5

主函数: 

#!/usr/bin/env python3
#find_all_routes_of_2_points.py
#fumiama 20201001
import sys
from graphviz import Digraph

def exitWithError(*error):
    print(*error)
    exit()

def printGraph2Pdf(grf): grf.render('graph-output/output.gv', view=True)

def printRoute(stackList):
    global nodeNumber
    nodeNumber += 1
    dot.node(str(nodeNumber), stackList[0])
    for node in stackList[1:]:
        nodeNumber += 1
        dot.node(str(nodeNumber), node)
        dot.edge(str(nodeNumber-1), str(nodeNumber))

def addEdge(a, b):
    global edgeLinks
    if a not in edgeLinks: edgeLinks[a] = set()
    if b not in edgeLinks: edgeLinks[b] = set()
    edgeLinks[a].add(b)
    edgeLinks[b].add(a)

def loadGraph(fileName):
    try: f = open(fileName, 'r')
    except: exitWithError("打开文件失败, 请检查文件名是否正确或程序是否有权限访问")
    global size, edgeLinks
    size, edgeCount = map(int, f.readline().split())
    print("节点:", size, "边数:", edgeCount)
    for i in range(1, size+1): dot.node(str(i), str(i))
    for i in range(edgeCount):
        a, b = f.readline().split()
        addEdge(a, b)
        dot.edge(a, b)
    re = f.readline()
    f.close()
    return re

def findAllRoutes(start, end):
    global edgeLinks, stack
    stack.append(start)
    if start == end:
        print("找到路径:", stack)
        printRoute(stack)
        stack.pop()
    else:
        for nextPoint in edgeLinks[start]:
            if nextPoint not in stack: findAllRoutes(nextPoint, end)
        stack.pop()

def rmRoute2Itself(start):
    for point in edgeLinks:
        if point != start and start in edgeLinks[point]:
            edgeLinks[point].remove(start)

if __name__ == '__main__':

    dot = Digraph(comment='Gragh2Print')
    dot.edge_attr.update(arrowhead='none')
    dot.graph_attr['rankdir'] = 'LR'

    edgeLinks = dict()
    size = 0

    stack = []
    nodeNumber = 0

    # sys = "D:find_all_routes_of_2_points.py pdf graph.txt"
    # if len(sys.argv) != 3: exitWithError("用法:", sys.argv[0], "[pdf|nopdf] 文件位置")
    a, b = loadGraph("graph.txt").split()
    print("起点:", a, "终点:", b)
    rmRoute2Itself(a)
    nodeNumber = size + 1
    findAllRoutes(a, b)
    print("生成pdf格式图形化报告...")
    printGraph2Pdf(dot)

就可以看到最后生成的结果了,

输出效果:

节点: 16 边数: 20
起点: 2 终点: 5
找到路径: ['2', '3', '5']
找到路径: ['2', '3', '4', '5']
找到路径: ['2', '3', '4', '7', '5']
找到路径: ['2', '3', '4', '9', '6', '5']
找到路径: ['2', '4', '5']
找到路径: ['2', '4', '7', '5']
找到路径: ['2', '4', '9', '6', '5']
找到路径: ['2', '4', '3', '5']
找到路径: ['2', '1', '5']
生成pdf格式图形化报告...

并且生成pdf文件, 

 打开pdf文件显示为:

ok,问题解决。

Traceback (most recent call last): File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\site-packages\graphviz\backend\execute.py", line 78, in run_check proc = subprocess.run(cmd, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\subprocess.py", line 548, in run with Popen(*popenargs, **kwargs) as process: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\subprocess.py", line 1026, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\subprocess.py", line 1538, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [WinError 2] 系统找不到指定的文件。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "c:\Users\Adam\Desktop\study\code\python\代码\模块、函数练习\graph测试\1.py", line 34, in <module> gra.view() ^^^^^^^^^^ File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\site-packages\graphviz\_tools.py", line 171, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\site-packages\graphviz\rendering.py", line 185, in view return self.render(filename=filename, directory=directory, view=True, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\site-packages\graphviz\_tools.py", line 171, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\site-packages\graphviz\rendering.py", line 122, in render rendered = self._render(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\site-packages\graphviz\_tools.py", line 171, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\site-packages\graphviz\backend\rendering.py", line 326, in render execute.run_check(cmd, File "C:\Users\Adam\AppData\Local\Programs\Python\Python311\Lib\site-packages\graphviz\backend\execute.py", line 81, in run_check raise ExecutableNotFound(cmd) from e graphviz.backend.execute.ExecutableNotFound: failed to execute WindowsPath('dot'), make sure the Graphviz executables are on your systems' PATH
03-18
<think>嗯,用户遇到了一个Python的报错,看起来是关于Graphviz的。首先,我要理解这个错误信息。错误提示是FileNotFoundError,说系统找不到指定的文件。然后下面的异常提到ExecutableNotFound,特别是'dot'这个命令。看起来是Graphviz的可执行文件没被正确安装或者路径没配置好。 用户可能是在使用graphviz库时调用了view()方法,导致程序试图运行dot命令来生成图像,但系统找不到这个可执行文件。这时候需要检查Graphviz是否已经安装在用户的电脑上,而不仅仅是Python的库。因为Pythongraphviz库只是封装了Graphviz的工具,需要底层的软件支持。 接下来,我应该分步骤给出解决方案。首先,确认用户是否安装了Graphviz软件。如果没有安装,需要指导他们去官网下载安装。然后,安装完成后,要确保将Graphviz的bin目录添加到系统的PATH环境变量中,这样Python才能找到dot等命令。 另外,可能用户已经安装了Graphviz,但路径没有正确配置。这时候需要教他们如何手动添加路径到系统环境变量,或者在使用Python代码时指定路径。例如,在代码中设置os.environ["PATH"] += os.pathsep + 'Graphviz的安装路径/bin'。 还要考虑到用户的操作系统是Windows,所以需要给出针对Windows的具体步骤。比如,默认安装路径可能在C:\Program Files\Graphviz之类的,但用户可能安装在其他位置,需要提醒他们找到正确的路径。 最后,建议用户测试安装是否成功,可以在命令行输入dot -V看看是否有版本信息,或者重新运行代码检查是否还有同样的错误。如果用户按照步骤操作后问题依旧,可能需要进一步检查路径是否正确,或者尝试重启电脑让环境变量生效。</think>这个错误提示说明系统找不到Graphviz的可执行文件。以下是逐步解决方案: **错误原因分析**: 1. 错误发生在调用`gra.view()`时 2. 核心错误是`ExecutableNotFound: failed to execute WindowsPath('dot')` 3. 表明Pythongraphviz库找不到Graphviz主程序的`dot`可执行文件 **解决方法**: 1. **安装Graphviz软件**(注意这是独立软件,不是Python库) - 访问官网下载:https://graphviz.org/download/ - 选择Windows版本安装包(稳定版推荐) - 按照向导完成安装,记住安装路径(默认路径是:`C:\Program Files\Graphviz`) 2. **配置系统环境变量** - 打开控制面板 → 系统和安全 → 系统 → 高级系统设置 - 点击"环境变量" → 在"系统变量"中找到Path → 点击编辑 - 添加Graphviz的bin目录路径(例如:`C:\Program Files\Graphviz\bin`) - 确认所有对话框 3. **验证安装**(需重启命令行/Python环境) - 打开CMD输入: ```bash dot -V ``` 应该显示类似:`dot - graphviz version x.x.x` 4. **Python环境确认** - 确保已安装graphviz库: ```bash pip install graphviz ``` 5. **代码测试**(新增测试代码): ```python import graphviz # 测试是否找到Graphviz dot = graphviz.Digraph() dot.node('A', 'Hello') dot.node('B', 'World') dot.edges(['AB']) dot.render('test.gv', view=True) # 应自动弹出PDF查看器 ``` **常见问题补充**: - 如果安装路径包含空格(如默认路径),建议改用无空格路径(如`C:\Graphviz`) - 如果使用虚拟环境,需在配置环境变量后重启IDE - 对于VSCode用户,需重启IDE才能使环境变量生效 - 如果仍有问题,尝试在代码中显式指定路径: ```python import os os.environ["PATH"] += os.pathsep + 'C:/Program Files/Graphviz/bin' ``` 完成上述步骤后,应该可以正常使用graphviz的可视化功能。如果问题依旧,请提供具体的Graphviz安装路径和Python版本信息以便进一步排查。
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值