如何为Graphviz中的每个节点添加标签?

2024-05-16 15:10:41 发布

您现在位置:Python中文网/ 问答频道 /正文

[编辑]这里是ps为我做的:

   PID TTY          TIME CMD
  3796 pts/0    00:00:00 bash
  4811 pts/0    00:00:00 ps

我从Graphviz开始,我想显示正在运行的进程的名称。我有一个脚本,显示他们的号码,我试图添加一个标签到每个节点

问题是只有last write标签显示在根节点上,我如何才能将标签写入每个节点

#!/usr/bin/env python3

from subprocess import Popen, PIPE, call
import re

dot = open("psgraph.dot", "w")
dot.write("digraph G {\n")

p = Popen("ps -fe", shell=True, stdout=PIPE)
psre = re.compile(r"\w+\s+(\d+)\s+(\d+)")

p.stdout.readline() # ignore first line
for line in p.stdout:
    match = psre.search(line.decode("utf-8"))
    if match:
        if int(match.group(2)) in (0, 2):
            continue
        dot.write ("  {1} -> {0}\n".format(match.group(1), match.group(2)))

for line in p.stdout:
    match = psre.search(line.decode("utf-8"))
    if match:
        if int(match.group(2)) in (0, 2):
            continue
        dot.write ("""1 [label="loop"]\n""")

dot.write("""1 [label="laste write"]}\n""")
dot.close()

call("dot -Tpdf -O psgraph.dot", shell=True)

Tags: inimportif节点matchstdoutlinegroup
1条回答
网友
1楼 · 发布于 2024-05-16 15:10:41

我猜是这样的:

# Update RE to capture command, too
psre = re.compile(r"\w+\s+(\d+)\s+(\d+)\s+\d+:\d+:\d+\s(\w+)")

# Collect labels
cmds = []
p.stdout.readline() # ignore first line
for line in p.stdout:
    match = psre.search(line.decode("utf-8"))
    if match:
        if int(match.group(2)) in (0, 2):
            continue
        dot.write ("  {1} -> {0}\n".format(match.group(1), match.group(2)))
        cmds.append((match.group(2), match.group(3)),)

for cmd, label in cmds:
    dot.write ("""{0} [label="{1}"]\n""".format(cmd, label))

很明显,我在猜测您到底想在第二个循环中写什么,或者在所有标签之前写所有节点是必要的还是有用的。如果你能用你想要的来更新这个问题,我想这应该不难

相关问题 更多 >