diagrams icon indicating copy to clipboard operation
diagrams copied to clipboard

Output diagram to stdout

Open ggrossetie opened this issue 3 years ago • 4 comments

Hello,

I'm building a command line interface on top of Diagrams and I would like to output the diagram to stdout (instead of writing a file to disk).

If we don't want to introduce an additional option on the Diagram class then we could use the following convention:

from diagrams import Diagram
from diagrams.aws.compute import EC2

with Diagram("Simple Diagram", filename="-"):
    EC2("web")

The value - means that the diagram will be written to stdout.

ggrossetie avatar Jun 13 '21 11:06 ggrossetie

You can use the dot attribute of the diagram to get its contents as PNG or other formats: png = diagram.dot.pipe(format="png").

pawamoy avatar Feb 27 '22 17:02 pawamoy

@pawamoy Interesting, could you please provide a complete example using the DSL with Diagram?

ggrossetie avatar Feb 27 '22 19:02 ggrossetie

from contextlib import suppress
from diagrams import Diagram
from diagrams.k8s.clusterconfig import HPA
from diagrams.k8s.compute import Deployment, Pod, ReplicaSet
from diagrams.k8s.network import Ingress, Service

# unfortunately it seems there's no public API to prevent diagram
# from creating the file itself, so we have to mock diagram.render
# as well as suppress the resulting FileNotFoundError
with suppress(FileNotFoundError):
    with Diagram("Exposed Pod with 3 Replicas", show=False) as diagram:
        diagram.render = lambda: None
        net = Ingress("domain.com") >> Service("svc")
        net >> [Pod("pod1"),
                Pod("pod2"),
                Pod("pod3")] << ReplicaSet("rs") << Deployment("dp") << HPA("hpa")

        with open("some_arbitrary_file.png", "wb") as fd:
            fd.write(diagram.dot.pipe(format="png"))
        # or simply print to stdout: print(diagram.dot.pipe(format="png"))

@mingrammer could you confirm there's no public API to prevent diagram from writing the diagram to disk?

pawamoy avatar Feb 27 '22 19:02 pawamoy

Indeed, is there a way to control the file generation from the command line ?

Kochise avatar Mar 27 '23 08:03 Kochise