【问题标题】:How to add a label to each node in Graphviz?如何为 Graphviz 中的每个节点添加标签?
【发布时间】:2019-12-04 10:19:12
【问题描述】:

[编辑]这里问的是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)

【问题讨论】:

  • 您可以轻松摆脱这两个shell=True 实例; Popen(['ps', '-fe'], stdout=PIPE)call(['dot', '-Tpdf', '-O', 'psgraph.dot'])。另见stackoverflow.com/questions/3172470/…
  • @tripleee 检查示例的编辑并感谢链接
  • 所以您的正则表达式正在提取 PID 和 TTY?第二个循环应该从每一行中提取更多内容,但您不知道如何为此创建正则表达式?
  • @tripleee 是的,我想在 graphviz 节点中显示 CMD 而不是 PID
  • 您的问题实际上与如何在 Graphviz 中执行此操作完全无关,您只需要 Python 正则表达式的帮助?

标签: python subprocess graphviz


【解决方案1】:

我猜是这样的:

# 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))

我显然是在猜测您到底想在第二个循环中写什么,或者实际上是否有必要或有用在所有标签之前编写所有节点。如果您可以在这里用您想要的内容更新问题,我想这应该不难。

【讨论】:

  • 它正在做我想要达到的目标,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 2016-07-25
  • 2011-07-30
  • 2014-05-25
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多